How to handle javascript events via WebBrowser control for WinForms

别等时光非礼了梦想. 提交于 2019-11-27 12:50:27

Calling C# from JavaScript

Simply put, you can expose a C# object to the WebBrowser that the JavaScript can call directly The WebBrowser class exposes a property called ObjectForScripting that can be set by your application and becomes the window.external object within JavaScript. The object must have the ComVisibleAttribute set true

C#:

 [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public class ScriptInterface
    {
        public void callMe()
        {
            … // Do something interesting
        }
    }

    webBrowser1.ObjectForScripting = new ScriptInterface();

Javascript:

window.external.callMe();

Calling JavaScript in a WebBrowser control from C#

This is code I have. In the DocumentCompleted event ('cause I'm getting a page from online)

var wb = (WebBrowser)sender
//Lots of other stuff
object obj = wb.Document.InvokeScript("MyFunctionName");

Create a function that returns whatever value you need and invoke away.

You can also inject a script into the page

string js = "function MyFunctionName(){alert('Yea!');}";
HtmlElement el = wb.Document.CreateElement("script");
IHTMLScriptElement element2 = (IHTMLScriptElement)el.DomElement;
element2.text = js;
head.AppendChild(el);

which can then be invoked. That's what I've done.

Ahmad

If your webBrowser control is in a form, you can do the following:

[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Form1
{

    public Form1()
    {
       InitializeComponent();
       webBrowser1.ObjectForScripting = this;
    }

    public void CallMe()
    {
        //.... this method can be called in javascript via window.external.CallMe();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!