Today in a project to make a WebBrowser in C #, and some places also need to interact with JS. So I looked up the information, found a lot of blogs mentioned but did not say the specific operation. So I'll just write it.
The development environment is visual Studio 2008. reading this article requires a foundation for C # and JavaScript development.
1. First create a new project and drag a webbrowser1 on the default form Form1.
2. Add the following code to the load time event for Form1:
Private void Form1_Load (object sender, EventArgs e) { this; }
3. Open Solution Explorer, right-click on the project and select Properties to open the project properties setting.
4. Click the assembly information in the Application tab and tick "make assembly COM visible".
After these basic settings, you can let WebBrowser and JS interact, the interactive method is as follows:
C # Method of invoking the JS function:
The method that is called by C # is first defined in JS: function MESSAGEAA (message) {alert (message);}
Call the JS method in C # MESSAGEAAPrivate voidButton1_Click (Objectsender, EventArgs e) { //Call the JavaScript MessageBox method and pass in the parameters Object[] objects =New Object[1]; objects[0] ="C#diao JavaScript"; WebBrowser1.Document.InvokeScript ("MESSAGEAA", objects);}
The method of invoking C # functions with JS:
First, define the method to be called by JS in C #: Public void Mymessagebox (string message) { MessageBox.Show (message);} Call C # method in JS:<!--call C # method--><button onclick="Window.external.MyMessageBox (' JavaScript access C #代码 ')' >javascript access C # code </button>
WebBrowser and JavaScript (JS) interaction in C #