如何在msHTML中调用脚本

本文关键字:调用 脚本 msHTML | 更新日期: 2023-09-27 18:02:50

我使用axWebBrowser,我需要使一个脚本的工作,当一个列表框的选择项目被改变。

在默认的webBrowser控件中有一个方法,如;

WebBrowserEx1.Document.InvokeScript("script")

但在axWebBrowser我不能工作任何脚本!并且没有关于这个控件的文档。

有人知道怎么做吗

如何在msHTML中调用脚本

一个迟来的答案,但希望仍然可以帮助别人。当使用WebBrowser ActiveX控件时,有许多方法可以调用脚本。同样的技术也可以用于WinForms版本的WebBrowser控件(通过WebBrowser . htmldocument . domdocument)和WPF版本(通过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);
}

必须至少有一个<script>标记才能使JavaScript的eval工作,它可以像上面所示的那样注入。

或者,JavaScript引擎可以异步初始化,如webBrowser.Document.InvokeScript("setTimer", new[] { "window.external.notifyScript()", "1" })webBrowser.Navigate("javascript:(window.external.notifyScript(), void(0))")