简体   繁体   中英

Using WPF to handle events from JavaScript hosted in WebBrowser control

I have a WebBrowser control hosted on a WPF page. I'm wondering if there is any way for a JavaScript function to call an event in the WPF program.

I have a button on the web page in the WebBrowser control:

<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:

        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:

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.

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?

Yes, you can.

The WebBrowser control has an ObjectForScripting property:

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.

ObjectForScripting is the answer. 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):

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. I don't think you can use any kind of FrameworkElement object as your ObjectForScripting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM