WebBrowser (IE) and JS call each other, webbrowserjs

Source: Internet
Author: User

WebBrowser (IE) and JS call each other, webbrowserjs

During development, we often embed the WebBrowser control into the Winform program to browse the Web page. Javascript is indispensable for Web pages. Let's talk about the mutual calls between them.

In the C # encapsulated browser kernel, Chromium kernel encapsulates Xilium. Cefglue, Cefsharp, and Webkit kernel encapsulates Webkit. Net and OpenWebKitSharp.

But when talking about JS calls, I have to say that IE's WebBrowser is the easiest and most convenient. I will write articles for analysis in the future as to why IE is convenient and inconvenient.

Next let's take a look at how WebBrowser interacts with JS:

WebBrowser executes JS Code

If the script already exists in the webpage, we can use the InvokeScript method.

 

public object InvokeScript(string scriptName)
public object InvokeScript(string scriptName,object[] args)

 

The following is a simple example:

 

[Html]View plain copy
  1. <HTML>
  2. <HEAD>
  3. <TITLE> Invoke Script Sample </TITLE>
  4. <SCRIPT>
  5. // Call without Parameters
  6. Function alertNull (){
  7. Alert ("WebBrowser call! ");
  8. }
  9. // Call with Parameters
  10. Function callWithPar (name, address ){
  11. Alert ("Name is" + name + "; address is" + address );
  12. }
  13. // Return a string
  14. Function returnString (){
  15. Return ("This is a test .");
  16. }
  17. // Return object
  18. Function returnScriptObject (){
  19. Return (new (MyObject ));
  20. }
  21. Function MyObject (){
  22. This. Data = "Data for my private object .";
  23. }
  24. </SCRIPT>
  25. </HEAD>
  26. <BODY>
  27. <DIV id = "div1">
  28. </DIV>
  29. </BODY>
  30. </HTML>

 

[Csharp]View plain copy
  1. Private void button2_Click (object sender, EventArgs e)
  2. {
  3. String name = "dai ";
  4. String address = "123 ";
  5. If (webBrowser1.Document! = Null)
  6. {
  7. HtmlDocument doc = webBrowser1.Document;
  8. // Call without Parameters
  9. Doc. InvokeScript ("alertNull ");
  10. Object [] objArray = new Object [2];
  11. ObjArray [0] = (Object) name;
  12. ObjArray [1] = (Object) address;
  13. // Call with Parameters
  14. Doc. InvokeScript ("callWithPar", objArray );
  15. // Return a string
  16. String str = doc. InvokeScript ("returnString"). ToString ();
  17. MessageBox. Show (str );
  18. // Return object
  19. Object jscriptObj = doc. InvokeScript ("returnScriptObject ");
  20. MessageBox. Show (jscriptObj. ToString ());
  21. }
  22. }

If the target script does not exist in the webpage, we can create the script and execute it again.

 

 

[Csharp]View plain copy
  1. HtmlElement ele = webBrowser1.Document. CreateElement ("script ");
  2. Ele. SetAttribute ("type", "text/javascript ");
  3. Ele. SetAttribute ("text", "alert ('new script ')");
  4. WebBrowser1.Document. Body. AppendChild (ele );

 

It is equivalent to modifying the DOM structure of Html. After the <Body> tag is added, the <Script> tag is executed. After the program is loaded, JS Code in text is executed.

 

JS call C # Method

 

Next, let's talk about how to call the methods provided by C # In JS.

 

public object ObjectForScripting {get;[SecurityCriticalAttribute]set;}

Objects of public instances are implemented by host applications and can be accessed by scripts in the host documents.

 

With this method, it is easy to call the C # method. You only need to declare a C # object in C #, and then set this. webBrowser1.ObjectForScripting = new JSObject (); then OK.

Remember to declare [System. Runtime. InteropServices. ComVisible (true)] on the JSObject class to make the object visible.

After setting, you can use Window. external. function (); In JS to call the function () method of JSObject.

The following is an example:

 

[Html]View plain copy
  1. <HTML>
  2. <HEAD>
  3. <TITLE> Invoke C # Sample </TITLE>
  4. </HEAD>
  5. <BODY>
  6. <DIV id = "div1">
  7. </DIV>
  8. <SCRIPT>
  9. Window. external. CallShow ();
  10. // PASS Parameters
  11. Window. external. ShowSomething ("Hello ");
  12. // Return Value
  13. Var msg = window. external. returnSomething ("Hello ");
  14. Alert (msg );
  15. // Directly obtain the variable
  16. Alert (window. external. );
  17. </SCRIPT>
  18. </BODY>
  19. </HTML>


[Csharp]View plain copy
  1. [System. Runtime. InteropServices. ComVisible (true)]
  2. Public class JSObject
  3. {
  4. // No parameter, no return value
  5. Public void CallShow ()
  6. {
  7. MessageBox. Show ("Called from JS ");
  8. }
  9. // No return value, with Parameters
  10. Public void ShowSomething (String msg)
  11. {
  12. MessageBox. Show ("Called from" + msg );
  13. }
  14. // Return value and Parameter
  15. Public string returnSomething (String msg)
  16. {
  17. Msg + = "From C #";
  18. Return msg;
  19. }
  20. // Directly obtain the variable
  21. Public string a = "";
  22. }


Simple value transfer is implemented in this way. However, it is not convenient to transfer complex objects that involve conversion between JS objects and C # objects. If you can use strings, use strings.

 

JSON transfer is a good choice. Both C # And JS have JSON conversion tools. You can try it.

Above!

 


 

Related Article

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.