2

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.

2 Answers 2

3

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");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wooah! You are really a expert with WebBrowser technologies! thanks!!
1

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

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

1 Comment

I don't think it will change the Document Text - but I believe you would be limited by the maximum url length.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.