简体   繁体   English

如何在不修改webbrowser控件中的文档的情况下注入并执行javascript函数?

[英]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.. 但是我不想对加载的文档进行任何修改,如set DocumentText ,创建新的脚本元素等。

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! 问题是Java将DomElement视为字符串!
I want to send DomElement object with a javascript function to do processing on DomElement in the script. 我想发送带有JavaScript函数的DomElement对象,以对脚本中的DomElement进行处理。

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

这样的事情应该在控件中执行javascript,而无需更改文档:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM