For C # And JS communication during webbrowser usage,Webbrowser must set the objectforscripting attribute. It is an object, which can be provided to the script access on the webpage loaded by the webbrowser control..
After setting the objectforscripting attribute of the webbrowser control, you also need to set the applicationProgramVisible to com, otherwise an exception will be thrown (the objectforscripting class must be visible to com. Make sure the object is public or consider adding the comvisible attribute to your class .), You can make the following settings:
[System. runtime. interopservices. comvisible (true)]
For example:
[Comvisible ( True )] Public Partial Class Form1: FORM { Public Form1 () {initializecomponent ();} Protected Override Void Onload (eventargs e ){Webbrowser1.objectforscripting = This ;Webbrowser1.Navigate( " Http://www.cnblogs.com/winzheng " ); Base . Onload (e );}}
To communicate with JS, use the invokescript method of the Document Object of webbrowser.
The method signature is as follows:
Invokescript (string spritename, object [] ARGs );
For example:
<Scripttype = " Text/JavaScript " > // Provided to C # Call Method Function Test (N, S) {alert (n + " / " + S );} // Call the C # Method Function callcsharp (){ // Here we can see what window. External is set. Alert (window. External );Window. External. Test( " Hello " , 15 );} </SCRIPT> <button onclick = " Callcsharp () " > Call C # </button>Call: Web. Document. invokescript ( " Test " , New Object [] { 1 , " Hello " });
Http://www.lwolf.cn/blog/article/code/WebBrowser-js-call-csharp.htm
Http://blog.udnz.com/Article/Invoke_Members_Of_Winform_On_Webbrowser.aspx