“指定的演员无效”使用 execScript 时
我试图在 IE 内的 iframe 上执行脚本,但我总是收到“指定的强制类型转换无效”:
IWebBrowser2 iWebBrowser2 = GetIframe(); //retrieve the iframe (saved in document complete event)
IHTMLDocument2 document = iWebBrowser2.Document as IHTMLDocument2;
document.parentWindow.execScript("alert('test');", "javascript");
当我尝试访问 document.parentWindow 时出现问题(甚至询问 document.parentWindow 是否为 null) )。
重要的是,我是从文档完成事件线程的不同线程中执行此操作的。
你能帮我解决这个问题吗?
谢谢,
奥姆里
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我怀疑与线程相关的问题。您不能只从不同的线程访问 MSHTML 接口,至少不能不进行一些编组。尝试在“文档完成事件线程”(又称主线程)上调用您的代码。
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.
虽然我之前使用过 IE,但我并不完全熟悉这个特定的用例。一些快速谷歌搜索发现了一个有趣的注释:
http:// /msdn.microsoft.com/en-us/library/aa752116(v=vs.85).aspx
如果您不安全地编写脚本并且 iWebBrowser2.Document 为空,这可能会导致您的问题?
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
If you're not safe for scripting and iWebBrowser2.Document is null, that might be causing your issue?
您是否考虑过 iframe 异步加载到主文档的事实?这意味着即使主文档可能已触发
documentCompleted
,但 iframe 很可能在接下来的几秒钟内仍不会加载。判断 iframe 是否已加载有点棘手,但您可以通过在实际调用之前引入人工延迟(a-la Timer)来测试您的方法,以便允许 iframe 首先加载。希望这有帮助。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.