[英]Using WPF to handle events from JavaScript hosted in WebBrowser control
I have a WebBrowser control hosted on a WPF page. 我在WPF页面上托管了一个WebBrowser控件。 I'm wondering if there is any way for a JavaScript function to call an event in the WPF program.
我想知道JavaScript函数是否有任何方法可以在WPF程序中调用事件。
I have a button on the web page in the WebBrowser control: 我在WebBrowser控件的网页上有一个按钮:
<button style="height:100;width:100" id="initButton" onclick="alert('hello');" />
In the WPF code, I've tried to hook an event on a button this way: 在WPF代码中,我试图通过这种方式在一个按钮上挂钩事件:
mshtml.HTMLButtonElementEvents_Event iEvent;
iEvent = (mshtml.HTMLButtonElementEvents_Event)ele;
iEvent.onclick += new HTMLButtonElementEvents_onclickEventHandler(ClickEventHandler);
...
private bool ClickEventHandler()
{
MessageBox.Show("WPF Event Handler");
return true;
}
and then call the onclick from my javascript function like this: 然后从我的javascript函数调用onclick,如下所示:
function SomeEvent(sender, e) {
alert('JS event handler');
document.getElementById("initButton").onclick();
}
The WPF code is called when I press the button but not when onclick is called from SomeEvent. 当我按下按钮时调用WPF代码,但是当从SomeEvent调用onclick时调用WPF代码。
Is there a simpler way to do this? 有更简单的方法吗? Is there a better way to call the onclick event from JS so the attached WPF attached event is called?
是否有更好的方法从JS调用onclick事件,以便调用附加的WPF附加事件?
Yes, you can. 是的你可以。
The WebBrowser
control has an ObjectForScripting
property: WebBrowser
控件具有ObjectForScripting
属性:
http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.objectforscripting.aspx http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.objectforscripting.aspx
javascript can call methods on that object, which can call methods on your wpf page to fire events, etc. javascript可以调用该对象上的方法,该方法可以调用wpf页面上的方法来触发事件等。
ObjectForScripting is the answer. ObjectForScripting 就是答案。 For convenience sake, here is a link to a Winforms example (I too am using WPF, but there is no example on the WPF page):
为方便起见,这里是Winforms示例的链接(我也使用WPF,但WPF页面上没有示例):
https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting(v=vs.110).aspx
For what it's worth, it did not work for me to set my main window as the ObjectForScripting. 对于它的价值,我将主窗口设置为ObjectForScripting并不起作用。 I don't think you can use any kind of FrameworkElement object as your ObjectForScripting.
我不认为您可以使用任何类型的FrameworkElement对象作为您的ObjectForScripting。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.