在做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
{
MapControl mainWindow;
public ObjectForScriptingHelper(MapControl main)//注意MapControl要写成你自己项目中的对象名
{
mainWindow = main;
}
//这个方法就是网页上要反问的方法
public void Hello(string cmd)
{
MessageBox.Show(cmd);
}
}
然后在我们的WPF窗体加上调用
ObjectForScriptingHelper helper = new ObjectForScriptingHelper(this);
webBrowser.ObjectForScripting = helper;
string url = "http://10.10.55.132:8089/Test/index-test1.html?t=" + DateTime.Now.Ticks; //解决缓存问题
this.webBrowser1.Navigate(url);
html代码:
<html>
<head>
<title>this is a test</title>
<script type ="text/javascript">
function Hello() {
window.external.Hello("hello test");//getDebugPath()为c#方法
//alert("hello");
}
</script>
</head>
<body>
<button onclick="Hello()">
hello test
</button>
</body>
</html>