从 WPF 中的 Web 浏览器调用 HTML 页面中存在的 JavaScript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14496108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call JavaScript function present in HTML page from web browser in WPF
提问by Mahesh
I am new to WPF. I am using "WebBroswer" in my wpf application to render a Google map. I have a googlemap.htm page and it contains a initialize(lat, log) JavaScript function. Now I want to call this function from my .xaml.cs file with lat and log parameters.
我是 WPF 的新手。我在 wpf 应用程序中使用“WebBroswer”来呈现 Google 地图。我有一个 googlemap.htm 页面,它包含一个 initialize(lat, log) JavaScript 函数。现在我想从我的 .xaml.cs 文件中使用 lat 和 log 参数调用这个函数。
Googlemap.htm
谷歌地图.htm
<script>
function initialize(lat, log) {
var mapProp = {
center: new google.maps.LatLng(lat, log),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
回答by SHSE
The easiest approach is to use WebBrowser.InvokeScriptmethod:
最简单的方法是使用WebBrowser.InvokeScript方法:
this.WebBrowser.InvokeScript("initialize", 1, 2);
Alternatively you could also rewrite you JavaScript code like this:
或者,您也可以像这样重写 JavaScript 代码:
function initialize(lat, log) {
var mapProp = {
center: new google.maps.LatLng(lat, log),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
document.myfunc = initialize; // expose it to the document scope
google.maps.event.addDomListener(window, 'load', initialize);
So now you can access myfuncfrom C# code:
所以现在您可以myfunc从 C# 代码访问:
private void WebBrowser_OnLoadCompleted(object sender, NavigationEventArgs e)
{
dynamic document = WebBrowser.Document;
document.myfunc(1, 2);
}
You could also invoke myfuncwithout dynamickeyword:
您也可以myfunc不带dynamic关键字调用:
private void WebBrowser_OnLoadCompleted(object sender, NavigationEventArgs e)
{
var document = this.WebBrowser.Document;
document.GetType().InvokeMember("myfunc", BindingFlags.InvokeMethod, null, document, new object[] {1, 2});
}

