如何System.Windows.Forms.WebBrowser调用自定义的Javascript? [英] How to invoke custom Javascript in System.Windows.Forms.WebBrowser?
问题描述
我加载一个包含下列code第三方网页
I'm loading third party webpage that contains following code
<script type="text/javascript">
onDomReady(function() { some_code1; });
</script>
到WebBrowser组件。经过 some_ code1
已经执行我需要做的Dom一些操作,这将使 some_ code1
无效。现在的问题是如何确定 some_ code1
已执行?
into WebBrowser component. After some_code1
had executed I need to do some manipulations with Dom that will make some_code1
invalid. The question is how to determine that some_code1
had executed?
我cant't做
private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
DoRequiredManipulations();
}
由于会发生此事件的在的 some_ code1
已执行,并使其无效。
Since this event will occur before some_code1
has executed and will make it invalid.
此外,我不能这样做。
private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
web.Document.InvokeScript("doSome_code1");
DoRequiredManipulations();
}
由于 some_ code1
声明为一个匿名函数。
Since some_code1
is declared as an anonymous function.
看来,做到这一点的唯一方法是这样的:
It seems that the only way to do it is this:
private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var script = GetScriptText(web.DocumentText);
//execute script in webbrowser
DoRequiredManipulations();
}
现在的问题是,我不知道如何在网页浏览器执行该脚本。我曾试图 web.Navigate(JavaScript的:+脚本);
,但它不能正常工作
The problem is that I don't know how to execute this script in webbrowser. I had tried web.Navigate("javascript: " + script);
but it doesn't work correctly.
推荐答案
我发现如何做到这一点:
I found how to do that:
HtmlElement scriptEl = web.Document.CreateElement("script");
(scriptEl.DomElement as IHTMLScriptElement).text = "function myscript() { " + script.Text + " }";
web.Document.GetElementsByTagName("head")[0].AppendChild(scriptEl);
web.Document.InvokeScript("myscript");
这篇关于如何System.Windows.Forms.WebBrowser调用自定义的Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!