I have a C# WinForms application that has a WebBrowser control inside of it. I would like to perform two-way communication between my C# form and the JavaScript within the embedded web browser control.
I know I can invoke a JavaScript function with InvokeScript, but how can I invoke C# code from JavaScript in a Document? I guess it wont be easy due to security, but is it possible, somehow, anyhow?
These JavaScript functions are supposed to be user functions, pretty much like macros, that would tell the WebBrowser exactly what to do with the help of a whole C# library written by myself. And since this is for a web scraper, JavaScript is the perfect language for these macros since it is pretty much made to access elements in an HTML document.
What you need to do is set the
ObjectForScriptingproperty on the web browser control to an object containing the C# methods you want to call from JavaScript. Then you can access that object from JavaScript usingwindow.external. The only thing to watch out for is that the object has to have the[ComVisibleAttribute(true)]attribute. I’ve used this successfully for several years.Here’s a page with documenation and a simple example: http://msdn.microsoft.com/en-us/library/a0746166.aspx
Here’s the example from the link (I haven’t tried this code):