How to inject Javascript in WebBrowser control

2019-01-18 16:28发布

问题:

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.

回答1:

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.



回答2:

The best answer I found on the net was from http://clistax.com/question/qt/153748/st/4eb64b29180c4

I believe the most simple method to inject Javascript in a WebBrowser Control HTML Document from c# is to invoke the "execStrip" method with the code to be injected as argument.

In this example the javascript code is injected and executed at global scope:

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

If you want to delay execution, inject functions and call them after:

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

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

This is valid for Windows Forms and WPF WebBrowser controls.

This solution is not cross browser because "execScript" is defined only in IE and Chrome. But the question is about Microsoft WebBrowser controls and IE is the only one supported.



回答3:

I found this that help that talks about invokescript eqivilent in wpf for just executing script code inside html: http://msdn.microsoft.com/en-us/library/cc452443.aspx