WTL IWebBrowser2调用网页中javascript函数

原帖网址:http://blog.csdn.net/tujiaw/article/details/6556880


1.简单的含有js的网页:

[javascript]  view plain copy
  1. <html>  
  2.     <head>  
  3.     <mce:script type = "text/javascript"><!--  
  4.     function test(){  
  5.     document.write("hello world!");  
  6.     }  
  7.     function test2(){  
  8.     alert("hello, world");  
  9.     }  
  10.     function link(){  
  11.     window.location.href = "http://www.baidu.com";  
  12.     }  
  13.     test();  
  14.       
  15. // --></mce:script>  
  16.     </head>  
  17.     <body>  
  18.         <p><a href = "javascript:link()">this is js link</a></p>  
  19.     </body>  
  20. </html>  

2.WebBrowser ActiveX控件成员变量:

[c-sharp]  view plain copy
  1. CComPtr<IWebBrowser2> m_pWb2;   

3.在OnInitDialog中

[c-sharp]  view plain copy
  1. CAxWindow wndIE = GetDlgItem(IDC_IE);     
  2. HRESULT hr;     
  3. hr = wndIE.QueryControl(&m_pWb2);     
  4. if (m_pWb2)     
  5. {     
  6.     CComVariant v;     
  7.     m_pWb2->Navigate(CComBSTR(_T("...//test.html")), &v, &v, &v, &v);   // 这里地址省略了,注意要用//  
  8. }   

4.在OnOk函数里测试

[c-sharp]  view plain copy
  1. LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)  
  2.     {  
  3.         // TODO: Add validation code   
  4.         HRESULT hr;  
  5.         CComPtr<IDispatch> spdispDoc;     
  6.         hr = m_pWb2->get_Document(&spdispDoc);  
  7.         if (FAILED(hr))     
  8.         {     
  9.             return hr;     
  10.         }     
  11.         CComQIPtr<IHTMLDocument2> spDoc = spdispDoc;  
  12.           
  13.         VARIANT ret;  
  14.         ret.vt = VT_EMPTY;  
  15.         return WtlCallJavascript(spDoc, CComBSTR("test2()"), &ret);  
  16.         //CloseDialog(wID); // 屏蔽掉回车关闭对话框  
  17.     }  

上面需要的函数

[c-sharp]  view plain copy
  1. LRESULT WtlCallJavascript(CComQIPtr<IHTMLDocument2> htmlDoc, BSTR strCode, VARIANT *pvarRet)  
  2. {  
  3.     HRESULT hr = -1;  
  4.     if (!(htmlDoc && strCode))  
  5.     {  
  6.         return hr;  
  7.     }  
  8.     IHTMLWindow2 *pHtmlWnd;  
  9.     hr = htmlDoc->get_parentWindow(&pHtmlWnd);  
  10.     if (SUCCEEDED(hr))  
  11.     {  
  12.         hr = pHtmlWnd->execScript(strCode, CComBSTR(_T("javascript")), pvarRet);  
  13.     }  
  14.     return hr;  
  15. }  

运行程序后它会打开我们的html网页, 然后按Enter键会弹出hello, world小的提示窗口说明js里的那个函数执行了。

 

插入WebBrowser控件的方法可以看这里:WTL 通过IWebBrowser2接口使WebBrowser控件在自己的窗口打开网页


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值