tzerb tzerb - 15 days ago 9
Javascript Question

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?

Answer

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.