3

这里有一个很棒的关于 windows 窗体的教程

如何在 WebBrowser 控件中注入 Javascript?

我试过了,效果很好

但问题是 wpf 应用程序无法识别那里使用的对象。所以我要问的是 wpf 应用程序中以下功能的等价物。谢谢你。

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
string srJquery = File.ReadAllText("jquery.txt");
element.text = srJquery;
head.AppendChild(scriptEl);  

上面的函数在 windows 窗体应用程序 c# 4.0 中完美运行,但在 WPF 应用程序中无法识别使用的对象,例如 HtmlElement。

4

4 回答 4

5

这行得通吗?

    private void WebBrowser_LoadCompleted
       (object sender,
        System.Windows.Navigation.NavigationEventArgs e)
    {
        var webBrowser = sender as WebBrowser;

        var document
           = webBrowser.Document as mshtml.HTMLDocument;
        var ahref
           = document.getElementsByTagName("A").Cast<mshtml.IHTMLElement>().First();
        ahref.setAttribute(
           "onmouseenter",
           "javascript:alert('Hi');", 1);
    }

您需要的是Microsoft.mshtml(.net API 而不是 MS office 之一)参考。

另请参阅 WPF webbrowser 控件的代码,该控件使用ObjectForScripting的属性WebBrowser可以帮助您注入 javascript...

http://blogs.msdn.com/b/wpf/archive/2011/05/27/how-does-wpf-webbrowser-control-handle-window-external-notify.aspx

让我知道这是否有帮助。

于 2011-11-04T07:07:23.093 回答
3

我在网上找到的最佳答案来自http://clistax.com/question/qt/153748/st/4eb64b29180c4

我相信从 c# 在 WebBrowser Control HTML 文档中注入 Javascript 的最简单方法是调用“execStrip”方法,并将要注入的代码作为参数。

在此示例中,javascript 代码在全局范围内注入和执行:

var jsCode="alert('hello world from injected code');";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });

如果你想延迟执行,注入函数并在之后调用它们:

var jsCode="function greet(msg){alert(msg);};";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });

WebBrowser.Document.InvokeScript("greet",new object[] {"hello world"});

这对 Windows 窗体和 WPF WebBrowser 控件有效。

此解决方案不是跨浏览器,因为“execScript”仅在 IE 和 Chrome 中定义。但问题是关于 Microsoft WebBrowser 控件,而 IE 是唯一受支持的控件。

于 2014-08-06T16:14:25.397 回答
1

动态使这很容易。您只需要记住我们正在使用Microsoft.mshtml.

private void wb_Navigated(object sender, NavigationEventArgs e)
{

    if (wb != null && wb.Document != null)
    {
        dynamic document = wb.Document;
        dynamic script = document.createElement("script");
        script.type = @"text/javascript";
        script.text = @"alert('hello world');";
        try { document.head.appendChild(script); } catch (Exception ex) { } // Dynamic property head does not exist.
    }
}

提示:确保您使用Navigated而不是Navigating确保文档已填充。

我发现自己经常设置script.text使用来加载本地 javascript 文件。System.IO.File.ReadAllText(pathToJs)由于嵌入式浏览器经常过时,因此将polyfill之类的东西注入我的 Windows 窗体和 WPFWebBrowser应用程序已成为我的标准。

于 2020-10-27T21:24:59.323 回答
0

我发现这有助于讨论 wpf 中的 invokescript equivilent 仅在 html 中执行脚本代码:http: //msdn.microsoft.com/en-us/library/cc452443.aspx

于 2012-03-21T14:40:00.463 回答