Use webbrowser for C # And JS Communication

Source: Internet
Author: User

1. Foreground call Background:

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

After setting the objectforscripting attribute of the webbrowser control, you also need to set the application to be visible to com. Otherwise, an exception will be thrown (the objectforscripting class must be visible to com. Make sure that the object is public or you want to add the comvisible attribute to your class). You can set it as follows: [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 );
}

Public void test ()
{

MessageBox. Show ("that's OK ");

}
} Then you can use Windows. External. Test (); To call the public method in the background.


2. Call the foreground at the background:

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 );

Example: <SCRIPT type = "text/JavaScript">

Function Test (N, S)

{

Alert (n + "/" + S );

}

</SCRIPT>

Call: webbrowser1.document. invokescript ("test", new object [] {1, "hello "});

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.