WPF的WebBrowser 里面使用JavaScript调用外部方法的决解方法

在原来的WinForm里 我们只要在窗体类设置的头部设置个 [System.Runtime.InteropServices.ComVisibleAttribute(true)]

然后 webBrowser1.ObjectForScripting = this; 

这样设置完后 页面上的JS就能访问我们程序里面的方法了,但是在WPF里如果这样设置的话会提示一大串错误提示:

执行了 QueryInterface 调用,请求提供 COM 可见的托管类“Cloud.MainWindow”的默认 IDispatch 接口。不过,由于该类没有显式默认接口,并且是从非 COM 可见的类“System.Windows.Window”派生的,QueryInterface 调用将失败。这样做的目的是避免非 COM 可见的基类受 COM 版本规则的约束。

为什么会出这个错误我也不清楚... 

然后Google下国外的网站发现了一种解决办法,新建一个类

[System.Runtime.InteropServices.ComVisibleAttribute(true)]//将该类设置为com可访问
public class ObjectForScriptingHelper
{
  MainWindow mainWindow;

  public ObjectForScriptingHelper(MainWindow main)
  {
    mainWindow = main;
  }

  //这个方法就是网页上要反问的方法
  public void HtmlCmd(string cmd)
  {

    MessageBox.Show(cmd);

  }
}

 

然后在我们的WPF窗体加上调用

ObjectForScriptingHelper helper = new ObjectForScriptingHelper(this);

this.webBrowser.ObjectForScripting = helper;

OK 这样就可以了!

posted @ 2012-03-29 10:27  Lonely Bandit  阅读(2724)  评论(3编辑  收藏  举报