从WPF中的Web浏览器调用HTML页面中存在的JavaScript函数 [英] Call JavaScript function present in HTML page from web browser in WPF
问题描述
我是WPF的新手。我在wpf应用程序中使用 WebBroswer来渲染Google地图。我有一个googlemap.htm页面,它包含一个initialize(lat,log)JavaScript函数。现在,我想从带有.lat和log参数的.xaml.cs文件中调用此函数。
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.
Googlemap.htm
Googlemap.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>
推荐答案
最简单的方法是使用 WebBrowser.InvokeScript
方法:
The easiest approach is to use WebBrowser.InvokeScript
method:
this.WebBrowser.InvokeScript("initialize", 1, 2);
或者,您也可以像这样重写JavaScript代码:
Alternatively you could also rewrite you JavaScript code like this:
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);
所以现在您可以从C#访问 myfunc
代码:
So now you can access myfunc
from C# code:
private void WebBrowser_OnLoadCompleted(object sender, NavigationEventArgs e)
{
dynamic document = WebBrowser.Document;
document.myfunc(1, 2);
}
您还可以调用 myfunc
不使用 dynamic
关键字:
You could also invoke myfunc
without dynamic
keyword:
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});
}
这篇关于从WPF中的Web浏览器调用HTML页面中存在的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!