I have been playing around with webkit.net in a c# win forms project, and love how easy it is to call JavaScript functions from within the C# program with:
browser.Document.InvokeScriptMethod("functionName", new object[]{"parameter1", "parameter2"});
Now the question is how to do this the other way round... Is there some sort of event listener that can listen for a javascript function call, or any way to invoke a c# method via the JavaScript running in the webkit browser?
The way I'm doing it at the moment it using a bad hack ... having a look at the available event listeners, I hooked up to the TitleChanged
event, and read the value of a hidden input
field in the html .... this is really bad and needs an actual solution.
Thanks in advance, - Greg.
public Form1()
{
InitializeComponent();
webKitBrowser1.Navigating += new WebBrowserNavigatingEventHandler(Form1_Navigating);
}
private void Form1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
string url = e.Url.ToString();
if (url.IndexOf("app://") > -1)
{
e.Cancel = true;
processRequest(url);
}
}
This may not pass your Ugly Hack test, but is an ancient method for processing requests from a .net embedded browser. Essentially you intercept a URL GET request in the browser. If the URL contains a keyword (such as app://), you cancel the GET and process the URL parameters. Returning a value, was traditionally accomplished by calling the Navigate Method, however, using the method you described in your post, you can just directly call a javascript function.
There is a fork on github that adds the support for this with a scripting object (works similar to standard winforms browser). When the browser loads you can set the scripting object, the class that will handle your js calls, by using webKitBrowser.ObjectForScripting = myObject. Then from js you can call the method by using window.external.foo(). Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With