Share: C # and JavaScript Functions call each other (the objectforscripting class must be visible to com. Make sure the object is public or consider adding the comvisible attribute to your class .)

Source: Internet
Author: User

For C # And JS communication during webbrowser usage,Webbrowser must set the objectforscripting attribute. It is an object, which can be provided to the script access on the webpage loaded by the webbrowser control..

After setting the objectforscripting attribute of the webbrowser control, you also need to set the applicationProgramVisible to com, otherwise an exception will be thrown (the objectforscripting class must be visible to com. Make sure the object is public or consider adding the comvisible attribute to your class .), You can make the following settings:

[System. runtime. interopservices. comvisible (true)]

For example:

[Comvisible ( True  )]  Public   Partial   Class  Form1: FORM {  Public Form1 () {initializecomponent ();}  Protected   Override   Void  Onload (eventargs e ){Webbrowser1.objectforscripting  = This  ;Webbrowser1.Navigate(  "  Http://www.cnblogs.com/winzheng  "  );  Base . Onload (e );}} 

To communicate with JS, use the invokescript method of the Document Object of webbrowser.

The method signature is as follows:

Invokescript (string spritename, object [] ARGs );

For example:

<Scripttype = "  Text/JavaScript  " > //  Provided to C # Call Method  Function Test (N, S) {alert (n + "  /  " + S );} //  Call the C # Method Function callcsharp (){ //  Here we can see what window. External is set.  Alert (window. External );Window. External. Test(  "  Hello  " , 15  );} </SCRIPT> <button onclick = "  Callcsharp ()  " > Call C # </button>Call: Web. Document. invokescript (  "  Test  " , New Object [] { 1 , "  Hello  " });

Http://www.lwolf.cn/blog/article/code/WebBrowser-js-call-csharp.htm

Http://blog.udnz.com/Article/Invoke_Members_Of_Winform_On_Webbrowser.aspx

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.