我正在使用的是 <\p>
SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer()
控制/自动化Internet Explorer的一个实例。在某些页面上,我想运行一个JavaScript函数(init()
)。似乎最好的方法是使用HtmlDocument
的InvokeScript
方法,我一直在尝试以下操作,但没有成功:
void ie_DocumentComplete(object pDisp, ref object URL)
{
System.Windows.Forms.HtmlDocument doc = ie.Document;
doc.InvokeScript("init");
}
这段代码失败是因为doc
为空。我似乎无法从ie.Document
中获取System.Windows.Forms.HtmlDocument
。除了尝试上述方法外,我还尝试了以下方法:
System.Windows.Forms.HtmlDocument doc2 = (System.Windows.Forms.HtmlDocument)ie.Document;
并且
System.Windows.Forms.HtmlDocument doc2 = ie.Document as System.Windows.Forms.HtmlDocument;
有没有什么想法可以让这个工作-或者更好的方式在页面上运行脚本?
谢谢!
编辑:
运行JavaScript函数的另一种方法似乎是:
SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer()
mshtml.HTMLDocument doc = ie.Document;
mshtml.IHTMLWindow2 win = doc.parentWindow as mshtml.IHTMLWindow2;
win.execScript("init();", "javascript");
但是这条线路
mshtml.IHTMLWindow2 win = doc.parentWindow as mshtml.IHTMLWindow2;
抛出一个错误,说它是一个无效的转换(InvalidCastException
) - 即使 IntelliSense(和 MSDN) 说 doc.parentWindow
是一个 IHTMLWindow2
。有什么想法吗?(我已经确保在运行该代码之前页面已经完全加载)