I'm using
SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer()
to control/automate an instance of internet explorer. On certain pages I'd like to run a javascript function (init()). It seems the best way to do this is to use an HtmlDocument's InvokeScript method and I've been trying the following with no luck:
void ie_DocumentComplete(object pDisp, ref object URL)
{
System.Windows.Forms.HtmlDocument doc = ie.Document;
doc.InvokeScript("init");
}
Which fails because 'doc' is null. I can't seem to get a System.Windows.Forms.HtmlDocument from ie.Document. Besides trying to above, I've also tried:
System.Windows.Forms.HtmlDocument doc2 = (System.Windows.Forms.HtmlDocument)ie.Document;
and
System.Windows.Forms.HtmlDocument doc2 = ie.Document as System.Windows.Forms.HtmlDocument;
Any ideas how I can get this to work - or an even better way to run scripts on the page?
Thanks!!
EDIT:
Another way to run a javascript function appears to be:
SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer()
mshtml.HTMLDocument doc = ie.Document;
mshtml.IHTMLWindow2 win = doc.parentWindow as mshtml.IHTMLWindow2;
win.execScript("init();", "javascript");
But the line
mshtml.IHTMLWindow2 win = doc.parentWindow as mshtml.IHTMLWindow2;
throws an error that it is an invalid cast (InvalidCastException) - even though IntelliSense (and msdn) say doc.parentWindow is a IHTMLWindow2. Any ideas? (Also I've made sure a page has been fully loaded before running that code)