Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload