如何在WebBrowser控件的JavaScript注入 [英] How to inject Javascript in WebBrowser control

查看:225
本文介绍了如何在WebBrowser控件的JavaScript注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个伟大的教程在这里对Windows窗体

There is a great tutorial here about windows forms

如何注入Javascript脚本在WebBrowser控件?

我尝试过了,它的伟大工程

I tried it and it works great

但问题是对象使用那里的WPF应用程序无法识别。那么,我问是什么,是在WPF应用程序下面的功能是一样的。谢谢

But the problem is the objects used there is not recognized at wpf application. So what i am asking is what is the equivalent of the function below in wpf application. Thank you.

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



上面的函数是在窗口正常使用窗体应用程序C#4.0,但使用的对象,如的HtmlElement不在WPF应用程序的认可。

the function above is working perfectly at windows form application c# 4.0 but the used objects such as HtmlElement is not recognized at WPF application.

推荐答案

请问这项工作?

    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办公室一个)引用。

You need is Microsoft.mshtml (the .net API and not MS office one) reference.

另外,请参阅使用WPF WebBrowser控件的代码 ObjectForScripting web浏览器的属性,它可以帮助你在注入的JavaScript ...

Also please see this code for WPF webbrowser control that uses ObjectForScripting property of WebBrowser which can help you in injecting javascript...

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

让我知道,如果这有助于。

Let me know if this helps.

这篇关于如何在WebBrowser控件的JavaScript注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆