Examples of c and javascript functions calling each other are Shared
- 2020-06-07 05:11:39
- OfStack
After setting the ObjectForScripting property of the webBrowser control, you also need to make the application visible to com or throw an exception (ObjectForScripting's classes must be visible to COM). Make sure the object is public, or consider adding the ComVisible attribute to your class. Can be set as follows:
[System.Runtime.InteropServices.ComVisible(true)]
Such as:
[ComVisible(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
webBrowser1.ObjectForScripting = this;
webBrowser1.Navigate("https://www.ofstack.com");
base.OnLoad(e);
}
}
To communicate with JS, use the InvokeScript method of the Document object of webBrowser.
The method is signed as follows:
InvokeScript(String spriteName,object[] args);
Such as:
<scripttype="text/javascript"> // To provide c# Method to call
function test(n,s){
alert(n+"/"+s);
} // call C# The method of
function callCSharp(){ // And you can see here window.external What is it set to
alert(window.external);
window.external.Test("hello",15);
}
</script>
<button onclick="callCSharp()">call c#</button>
Call: web.Document.InvokeScript("test", new Object[] {1,"hello"});