Search code examples
internet-explorercastingihtmldocument2

"specified cast not valid" when using execScript


I'm trying to execute a script on an iframe inside IE but i get "specified cast not valid" all the time:

IWebBrowser2 iWebBrowser2 = GetIframe(); //retrieve the iframe (saved in document complete event) 
IHTMLDocument2 document = iWebBrowser2.Document as IHTMLDocument2; 
document.parentWindow.execScript("alert('test');", "javascript"); 

The problem occurs when i'm trying to access the document.parentWindow (even asking if document.parentWindow != null).

It's important so say that i'm doing it from a different thread that the document complete event thread.

can you help me with this problem?

Thanks,

Omri


Solution

  • I suspect a thread-related issue. You can't just access the MSHTML interfaces from different threads, at least not without doing some marshalling. Try invoking your code on the "document complete event thread" a.k.a. main thread.