Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke C# code from JavaScript in a Document in a WebBrowser

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.

like image 928
Juan Avatar asked Sep 12 '10 06:09

Juan


People also ask

What is invoke in C?

C/Invoke is a library for connecting to C libraries at runtime. This differs from the typical method of interfacing with C, which involves writing static definitions which are then compiled to a machine-dependant format.

What does invoking a method mean?

To "invoke" appears to mean to call a method indirectly through an intermediary mechanism.

What is invoke delegate C#?

19.6 Delegate invocation C# provides special syntax for invoking a delegate. When a non- null delegate instance whose invocation list contains one entry, is invoked, it invokes the one method with the same arguments it was given, and returns the same value as the referred to method.

Why invoke is used?

Invoke is used of putting into effect or calling upon such things as laws, authority, or privilege (“the principal invoked a rule forbidding students from asking questions”). Evoke is primarily used in the sense “to call forth or up” and is often found in connection with such things as memories, emotions, or sympathy.


2 Answers

What you need to do is set the ObjectForScripting property 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 using window.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):

using System; using System.Windows.Forms; using System.Security.Permissions;  [PermissionSet(SecurityAction.Demand, Name="FullTrust")] [System.Runtime.InteropServices.ComVisibleAttribute(true)] public class Form1 : Form {     private WebBrowser webBrowser1 = new WebBrowser();     private Button button1 = new Button();      [STAThread]     public static void Main()     {         Application.EnableVisualStyles();         Application.Run(new Form1());     }      public Form1()     {         button1.Text = "call script code from client code";         button1.Dock = DockStyle.Top;         button1.Click += new EventHandler(button1_Click);         webBrowser1.Dock = DockStyle.Fill;         Controls.Add(webBrowser1);         Controls.Add(button1);         Load += new EventHandler(Form1_Load);     }      private void Form1_Load(object sender, EventArgs e)     {         webBrowser1.AllowWebBrowserDrop = false;         webBrowser1.IsWebBrowserContextMenuEnabled = false;         webBrowser1.WebBrowserShortcutsEnabled = false;         webBrowser1.ObjectForScripting = this;         // Uncomment the following line when you are finished debugging.         //webBrowser1.ScriptErrorsSuppressed = true;          webBrowser1.DocumentText =             "<html><head><script>" +             "function test(message) { alert(message); }" +             "</script></head><body><button " +             "onclick=\"window.external.Test('called from script code')\">" +             "call client code from script code</button>" +             "</body></html>";     }      public void Test(String message)     {         MessageBox.Show(message, "client code");     }      private void button1_Click(object sender, EventArgs e)     {         webBrowser1.Document.InvokeScript("test",             new String[] { "called from client code" });     } } 
like image 65
Gabe Avatar answered Oct 02 '22 19:10

Gabe


You're probably looking for http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting.aspx

WebBrowser.ObjectForScripting lets you expose an instance of a [ComVisible] .net class to javascript code running inside the hosted web browser. It is exposed in javascript as window.external

Excellent article from Microsoft: How to: Implement Two-Way Communication Between DHTML Code and Client Application Code

like image 33
blucz Avatar answered Oct 02 '22 17:10

blucz