none
SHDocVw.InternetExplorer对象获取parentWindow总是报InvalidCastException异常 RRS feed

  • 问题

  • 各位好:

    最近想用SHDocVw.InternetExplorer来操作IE浏览器,执行JS,在调用SHDocVw.InternetExplorer document.parentWindow.execScript("js代码")的时候取parentWindow时总报InvalidCastException转换错误异常,一直找不到这方面的资料,如果有高手用过或了解这个类的请指点一下,关键代码如下:

    InternetExplorer ie=...//取到IE浏览器对象 
    IHTMLDocument2 document2 = (IHTMLDocument2)ie.Document;
    IHTMLWindow2 win = document2.parentWindow; //这里总是报InvalidCastException转换错误
    win.execScript("alert('aa')", "javascript");//使用JS

    谢谢!!!!

    2014年9月21日 16:20

答案

  • 你好,

    这问题好像跟线程有关,你可以试着在STA thread 里面获取 document.parentWindow

    private WebBrowser _webBrowser; //initialize this somewhere
    
      private void ExecuteJavaScript()
      {
         Thread aThread = new Thread(ExecuteJavaScriptWorker);
         aThread.SetApartmentState(ApartmentState.STA);
         aThread.Start(); 
      }
    
      private void ExecuteJavaScriptWorker()
      {
          HTMLDocument _document = _webBrowser.Document;
          _document.parentWindow.execScript("alert('Arbitrary javascript code')", "javascript");
      }

    详细信息,请参考这里:

    http://stackoverflow.com/questions/3514945/running-a-javascript-function-in-an-instance-of-internet-explorer


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2014年9月22日 7:38

全部回复

  • 你好,

    这问题好像跟线程有关,你可以试着在STA thread 里面获取 document.parentWindow

    private WebBrowser _webBrowser; //initialize this somewhere
    
      private void ExecuteJavaScript()
      {
         Thread aThread = new Thread(ExecuteJavaScriptWorker);
         aThread.SetApartmentState(ApartmentState.STA);
         aThread.Start(); 
      }
    
      private void ExecuteJavaScriptWorker()
      {
          HTMLDocument _document = _webBrowser.Document;
          _document.parentWindow.execScript("alert('Arbitrary javascript code')", "javascript");
      }

    详细信息,请参考这里:

    http://stackoverflow.com/questions/3514945/running-a-javascript-function-in-an-instance-of-internet-explorer


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2014年9月22日 7:38
  • 非常感谢,可以执行JS了,但执行的JS函数取不到返回值。

    2014年9月22日 13:55