Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

c# - How to inject Javascript in WebBrowser control

There is a great tutorial here about windows forms

How to inject Javascript in WebBrowser control?

I tried it and it works great

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Does this work?

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...