"specified cast not valid" when using execScript

Add-in Express™ Support Service
That's what is more important than anything else

"specified cast not valid" when using execScript
 
Omri Suissa




Posts: 137
Joined: 2011-10-17
Hi,
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
Posted 25 Oct, 2011 03:39:59 Top
Sergey Grischenko


Add-in Express team


Posts: 7224
Joined: 2004-07-05
Hi Omri.

Why don't you use IEApp to access the browser and root document?
Posted 25 Oct, 2011 11:35:09 Top
Omri Suissa




Posts: 137
Joined: 2011-10-17
as i wrote i'm trying to run it on an iframe
Posted 27 Oct, 2011 04:55:33 Top
Sergey Grischenko


Add-in Express team


Posts: 7224
Joined: 2004-07-05
Hi Omri,

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

I think that MSHTML is not designed to access it from a separate thread. At the moment I don't have a solution for this issue.
Posted 27 Oct, 2011 05:36:00 Top
Omri Suissa




Posts: 137
Joined: 2011-10-17
Hi Sergey,
you are right, MSHTML is not design to access it from a separate thread.
I found a solution by saving the original thread dispatcher and invoking a method on it from the separate thread:


IEModule_DocumentComplete(object pDisp, string url)
{
...
_objDocumentCompleteThreadDispatcher = Dispatcher.CurrentDispatcher;
...
}

// from a separate thread:
private static object ExecScript()
{
_objDocumentCompleteThreadDispatcher.Invoke(new MethodInvoker(delegate()
{
IWebBrowser2 iWebBrowser2 = GetIframe(); //retrieve the iframe (saved in document complete event) 
IHTMLDocument2 document = iWebBrowser2.Document as IHTMLDocument2; 
document.parentWindow.execScript("alert('test');", "javascript"); 
}));
}



it not optimal, there is another solution by using COM CoMarshalInterThreadInterfaceInStream but i think the first one i better.

Omri
Posted 27 Oct, 2011 06:13:14 Top
Sergey Grischenko


Add-in Express team


Posts: 7224
Joined: 2004-07-05
Hi Omri,

Thank you very much for sharing your solution.
Posted 27 Oct, 2011 11:12:35 Top
Omri Suissa




Posts: 137
Joined: 2011-10-17
NP :)
Posted 30 Oct, 2011 02:22:39 Top