Omri
Omri

Reputation: 915

"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

Upvotes: 2

Views: 1580

Answers (3)

XDS
XDS

Reputation: 4208

Have you taken into account the fact that iframes load asynchronously to the main document? Meaning that even though documentCompleted may have fired for the main document, the iframes most probably still won't be loaded for quite some seconds down the road. It's a bit tricky to tell whether an iframe has loaded or not but you can test your method by introducing an artificial delay (a-la Timer) before you actually call it, so as to allow the iframe to load first. Hope this helps.

Upvotes: 1

Heinrich Ulbricht
Heinrich Ulbricht

Reputation: 10362

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.

Upvotes: 2

Spyder
Spyder

Reputation: 1902

While I have worked with IE before I'm not totally familiar with this specific use case. Some quick googling turns up an interesting note:

http://msdn.microsoft.com/en-us/library/aa752116(v=vs.85).aspx

Warning If the document object type is not safe for scripting, this method returns successfully but sets ppDisp to NULL.

If you're not safe for scripting and iWebBrowser2.Document is null, that might be causing your issue?

Upvotes: 1

Related Questions