Mohsen Sarkar
Mohsen Sarkar

Reputation: 6030

How to inject and execute a javascript function without modifiting document in webbrowser control?

I could simply do :

object DomElement = ChooseMyDomElement(webBrowser1);  //this is a ID less element
webBrowser1.DocumentText = NewDocumentTextWithInjectedJavaScriptFunction;
webBrowser1.Document.InvokeScript("myfnc", DomElement);

However I don't want to make any modification to loaded document like set DocumentText, Create a new script element, etc..

Here is that I tried :

object DomElement = ChooseMyDomElement(webBrowser1);  //this is a ID less element
var js = "function myfnc(r) {alert(r);}  myfnc(" + DomElement +");"; //DomElement is converted to string!
webBrowser1.Document.InvokeScript("eval", new object[] { js });

The problem is that java sees DomElement as string!
I want to send DomElement object with a javascript function to do processing on DomElement in the script.

Upvotes: 2

Views: 1352

Answers (2)

noseratio
noseratio

Reputation: 61666

Try this:

void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    var anyScripts = webBrowser1.Document.GetElementsByTagName("script");
    if (anyScripts == null || anyScripts.Count == 0)
    {
        // at least one <script> element must be present for eval to work
        var script = webBrowser1.Document.CreateElement("script");
        webBrowser1.Document.Body.AppendChild(script);
    }

    // use anonymous functions

    dynamic func = webBrowser1.Document.InvokeScript("eval", new[] { 
        "(function() { return function(elem, color) { elem.style.backgroundColor = color; } })()" });

    var body = this.webBrowser1.Document.Body.DomElement;

    func(body, "red");
}

Upvotes: 3

Newse
Newse

Reputation: 2338

Something like this should execute javascript in the control without having to alter the document:

 BrowserControl.Navigate("javascript:function test(){console.log('test');}test();")

Upvotes: 1

Related Questions