我可以简单地做:
object DomElement = ChooseMyDomElement(webBrowser1); //this is a ID less element
webBrowser1.DocumentText = NewDocumentTextWithInjectedJavaScriptFunction;
webBrowser1.Document.InvokeScript("myfnc", DomElement);
但是我不想对加载的文档进行任何修改,例如set
DocumentText
,创建新的脚本元素等。这是我尝试过的:
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 });
问题是java将
DomElement
视为字符串!我想发送带有JavaScript函数的
DomElement
对象以在脚本中的DomElement
上进行处理。 最佳答案
尝试这个:
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");
}
关于c# - 如何在不修改webbrowser控件中的文档的情况下注入(inject)并执行javascript函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21871643/