In the WinForm project to embed the Web page, want to call the background method through the HTML page, how to implement it? Actually very simple, there are three main parts:
1. Add the [ComVisible (true)] label to the called Method class, meaning that the current class can be used as a COM component for outsourcing calls
2. Set the class that can be called by the HTML page in the WebBrowser control: webbrowser1.objectforscripting = this; the front end can access the This object through window.external
3, the HTML page calls the background method: Window.External. Method Name (); The window.external here is equivalent to webbrowser1.objectforscripting
1 //ComVisible Set External accessibility, you can use JS to access member methods in HTML2[ComVisible (true)]3 Public Partial classForm1:form4 {5 PublicForm1 ()6 {7 InitializeComponent ();8 }9 Ten Private voidForm1_Load (Objectsender, EventArgs e) One { A //Browser. URL = new Uri ("https://www.baidu.com"); -Browser. URL =NewUri ("http://localhost:3133/index.html"); -Browser. ObjectForScripting = This; the } - - Private voidbtnSearch_Click (Objectsender, EventArgs e) - { +HtmlElement kw = Browser. document.all["kw"]; -HtmlElement btn = browser. document.all["su"]; + A stringTXT =TXTWD. Text.trim (); atkw. SetAttribute ("value", TXT); -Btn. InvokeMember ("Click"); - } - - Private voidBtndo_click (Objectsender, EventArgs e) - { in int[] arr = {1, at }; -Browser. Document.invokescript ("F",New Object[] {"{ A-i}" }); to } + - Public voidWinf (stringArg) the { * MessageBox.Show (ARG); $ }Panax Notoginseng}
HTML code:
<! DOCTYPE Html>"Content-type"Content="text/html; Charset=utf-8"/> <title></title> <meta charset="Utf-8"/>"ext ()">external</button> <script>varf =function (msg) {//if ()Alert (Object.prototype.toString.call (msg)); } //call a method in WinFormfunction ext () {//call a method in WinFormWindow.external.WinF ("Hello"); } </script></body>[winform-webbrowser]-in HTML page JS call Winform class method