Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Javascript events via WebBrowser control for WinForms

I have read WebBrowser Control from .Net — How to Inject Javascript, Is it possible to call Javascript method from C# winforms and many others. Those examples were returns function value or alert window (synchronous calls). I have to get result from event handler (async call):

<script type="text/javascript">
        window.onload = function() {
            var o = new M.Build(document.getElementById("ZID"));

            M.Events.observe(o, o.Events.Success, function() {
                // I have to get some value!!
            });

            M.Events.observe(o, o.Events.Fault, function() {
                // I have to get some value!!
            });
        }
    </script>
like image 766
garik Avatar asked Mar 02 '11 12:03

garik


2 Answers

Calling C# from JavaScript

Simply put, you can expose a C# object to the WebBrowser that the JavaScript can call directly The WebBrowser class exposes a property called ObjectForScripting that can be set by your application and becomes the window.external object within JavaScript. The object must have the ComVisibleAttribute set true

C#:

 [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public class ScriptInterface
    {
        public void callMe()
        {
            … // Do something interesting
        }
    }

    webBrowser1.ObjectForScripting = new ScriptInterface();

Javascript:

window.external.callMe();

Calling JavaScript in a WebBrowser control from C#

like image 54
garik Avatar answered Nov 11 '22 09:11

garik


This is code I have. In the DocumentCompleted event ('cause I'm getting a page from online)

var wb = (WebBrowser)sender
//Lots of other stuff
object obj = wb.Document.InvokeScript("MyFunctionName");

Create a function that returns whatever value you need and invoke away.

You can also inject a script into the page

string js = "function MyFunctionName(){alert('Yea!');}";
HtmlElement el = wb.Document.CreateElement("script");
IHTMLScriptElement element2 = (IHTMLScriptElement)el.DomElement;
element2.text = js;
head.AppendChild(el);

which can then be invoked. That's what I've done.

like image 39
QuinnG Avatar answered Nov 11 '22 09:11

QuinnG