1. Create a webpage
<Html>
<Head>
<Meta http-equiv = "Content-Language" content = "zh-cn">
<Script language = "javascript" type = "text/javascript">
<! -- Provided to C # Program Calling Method -->
Function messageBox (message)
{
Alert (message );
}
</Script>
</Head>
<Body>
<! -- Call C # Method -->
<Button onclick = "window. external. MyMessageBox ('javascript access C # Code')">
Javascript access C # Code </button>
</Body>
</Html>
2. Create a Windows Application
1. Create a Windows Application Project
2. Add the WebBrowser control to the Form1 form.
3. Add
[System. Runtime. InteropServices. ComVisibleAttribute (true)]
This is to set this class to com accessible. If this statement is not performed, an error occurs. Shows the error information:
For example:
[System. Runtime. InteropServices. ComVisibleAttribute (true)]
Public partial class Form1: Form
4. initialize the Url and ObjectForScripting attributes of WebBrowser.
Url property: the webpage path displayed by the WebBrowser Control
ObjectForScripting property: This object can be accessed by the script code contained in the webpage displayed in the WebBrowser control.
Set the Url attribute to the URL path of the page to be operated.
JavaScript calls the C # public method through window. external. This is the public method contained in the instance of the class set by the ObjectForScripting attribute. The specific settings are as follows:
System. IO. FileInfo file = new System. IO. FileInfo ("index.htm ");
// Web page path displayed by the WebBrowser Control
WebBrowser1.Url = new Uri (file. FullName );
// Set the current class to be accessed by a script
WebBrowser1.ObjectForScripting = this;
5. C # Call the JavaScript Method
Use the InvokeScript method in the Document attribute of the WebBrowser class to call the Javascript method of the current webpage. For example:
// Call the messageBox method of JavaScript and input parameters
Object [] objects = new object [1];
Objects [0] = "C # accessing JavaScript scripts ";
WebBrowser1.Document. InvokeScript ("messageBox", objects );
The complete code is as follows:
[System. Runtime. InteropServices. ComVisibleAttribute (true)]
Public partial class Form1: Form
{
Public Form1 ()
{
InitializeComponent ();
System. IO. FileInfo file = new System. IO. FileInfo ("index.htm ");
// Web page path displayed by the WebBrowser Control
WebBrowser1.Url = new Uri (file. FullName );
// Set the current class to be accessed by a script
WebBrowser1.ObjectForScripting = this;
}
Private void button#click (object sender, EventArgs e)
{
// Call the messageBox method of JavaScript and input parameters
Object [] objects = new object [1];
Objects [0] = "C # accessing JavaScript scripts ";
WebBrowser1.Document. InvokeScript ("messageBox", objects );
}
// Method provided for JavaScript call
Public void MyMessageBox (string message)
{
MessageBox. Show (message );
}
}