WebBrowser and JavaScript (JS) interaction in C #

Source: Internet
Author: User

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 #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.