0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.