How to invoke scripts work in msHTML

ぐ巨炮叔叔 提交于 2019-12-17 05:14:26

问题


I'm using axWebBrowser and I need to make a script work which works when selected item of a listbox is changed.

In default webBrowser control there is a method like;

WebBrowserEx1.Document.InvokeScript("script")

But in axWebBrowser I can not work any script! And there is no documentation about this control.

Anyone knows how ?


回答1:


A late answer, but hopefully still may help someone. There is a number of ways to invoke a script when using WebBrowser ActiveX control. The same techniques can also be used with WinForms version of WebBrowser control (via webBrowser.HtmlDocument.DomDocument) and with WPF version (via webBrowser.Document):

void CallScript(SHDocVw.WebBrowser axWebBrowser)
{
    //
    // Using C# dynamics, which maps to COM's IDispatch::GetIDsOfNames, 
    // IDispatch::Invoke
    //

    dynamic htmlDocument = axWebBrowser.Document;
    dynamic htmlWindow = htmlDocument.parentWindow;
    // make sure the web page has at least one <script> tag for eval to work
    htmlDocument.body.appendChild(htmlDocument.createElement("script"));

    // can call any DOM window method
    htmlWindow.alert("hello from web page!");

    // call a global JavaScript function, e.g.:
    // <script>function TestFunc(arg) { alert(arg); }</script>
    htmlWindow.TestFunc("Hello again!");

    // call any JavaScript via "eval"
    var result = (bool)htmlWindow.eval("(function() { return confirm('Continue?'); })()");
    MessageBox.Show(result.ToString());

    //
    // Using .NET reflection:
    //

    object htmlWindowObject = GetProperty(axWebBrowser.Document, "parentWindow");

    // call a global JavaScript function
    InvokeScript(htmlWindowObject, "TestFunc", "Hello again!");

    // call any JavaScript via "eval"
    result = (bool)InvokeScript(htmlWindowObject, "eval", "(function() { return confirm('Continue?'); })()");
    MessageBox.Show(result.ToString());
}

static object GetProperty(object callee, string property)
{
    return callee.GetType().InvokeMember(property,
        BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public,
        null, callee, new Object[] { });
}

static object InvokeScript(object callee, string method, params object[] args)
{
    return callee.GetType().InvokeMember(method,
        BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public,
        null, callee, args);
}

There has to be at least one <script> tag for JavaScript's eval to work, which can be injected as shown above.

Alternatively, JavaScript engine can be initialized asynchronously with something like webBrowser.Document.InvokeScript("setTimer", new[] { "window.external.notifyScript()", "1" }) or webBrowser.Navigate("javascript:(window.external.notifyScript(), void(0))").



来源:https://stackoverflow.com/questions/15273311/how-to-invoke-scripts-work-in-mshtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!