现在的位置: 首页 > 综合 > 正文

BHO 动态添加元素

2013年09月07日 ⁄ 综合 ⁄ 共 2408字 ⁄ 字号 评论关闭

[动态添加元素]

insertAdjacentHTML 方法:

 (1) 得到 document 对象

  // 创建 CComPtr类型对象 spDisp ,  spDisp 包含 IDISPATCH 指针
 CComPtr<IDispatch> spDisp ;

 HRESULT hr = this->mWebBrowser2->get_Document(  &spDisp );
 if ( SUCCEEDED(hr) && spDisp )
 {
  // 调用 spDisp 的 QueryInterface 方法,  获得 IHTMLDOCUMENT2 指针, 存储在 spDoc .
  CComQIPtr< IHTMLDocument2 , &IID_IHTMLDocument2> spDoc( spDisp );

  if ( spDoc )
  {
     CComPtr < IHTMLElement> pBodyElement ;

    if ( SUCCEEDED( hr ) )
    {
     _bstr_t bstrState;
     
     spDoc->get_readyState( &bstrState.GetBSTR());
     if ( SUCCEEDED( hr ))
     { 
        /*
         * 检查文档是否加载完毕
         */ 
       if ( 0 == strcmp ( (char *)bstrState, "complete") )
       {
                /*
                 * 此处添加元素
                 */
       }
       
     }
   }
  }
  (2) 动态添加元素((1)中已经得到 Document 对象 )

  CComPtr<IHTMLElement>    spBodyElem;
  HRESULT hr = spDoc->get_body(&spBodyElem);
  if ( FAILED(hr) || !spBodyElem )
   return hr;

  HRESULT hr ;
  hr = spBodyElem->insertAdjacentHTML(L"afterBegin", _bstr_t("<img src="D://insert.bmp"></img>") );    

(3) 验证是否添加成功:

  CComPtr< IHTMLElement > pHtmlBody ;
  _bstr_t strText;
  spDoc->get_body( &pHtmlBody );
  pHtmlBody->get_outerHTML( &strText.GetBSTR() ) ;  //测试一下 strText 即可

 createElement,appendChild 方法:

 (1) 动态添加元素

 HRESULT hr ;
 CComPtr< IHTMLElement > pElement;

 //
 // 采用 createElment 添加图片成功
 //
 hr = pDoc->createElement( _bstr_t("<img src=/"D://new.bmp/"><img>"), &pElement );
 if ( FAILED(hr) )
 {
  ::AfxMessageBox("createElement Error") ;
  return hr;
 }

 // 通过 Body 元素的结点 
 CComPtr<IHTMLElement>    pBodyElem;
 hr = pDoc->get_body(&pBodyElem);
 if ( FAILED(hr) || !pBodyElem )
     return hr ;
 
 CComQIPtr< IHTMLDOMNode, &IID_IHTMLDOMNode >    pBodyNode(pBodyElem);
 if ( !pBodyNode )
  return hr;

 // 得到新建元素的结点
 CComQIPtr< IHTMLDOMNode, &IID_IHTMLDOMNode >    pNewChild(pElement);
 CComPtr< IHTMLDOMNode >    pRefChild;
 
 hr = pBodyNode->appendChild( pNewChild, &pRefChild );
 if ( FAILED(hr) || !pRefChild )
     return hr;

 

  (2)测试是否添加成功  

CComPtr< IHTMLElementCollection >  pElmentCollection;
 long num;
 pDoc->get_scripts( &pElmentCollection );
 
 pElmentCollection ->get_length( &num );
 
 
 _variant_t vName ;
 _variant_t vIndex ;
 vName.vt = VT_I4 ;  
 vIndex.vt = VT_I4 ;
 
  long count, index ;
  
  count = pElmentCollection->get_length( &count ) ;
  
  for ( index = 0; index < count; index++ )
  {
    vIndex.lVal = index ;
    vName.lVal  = index ;
    
    CComPtr<IDispatch > pDisp;
    pElmentCollection->item( vName , vIndex , &pDisp);

    CComQIPtr< IHTMLElement,  &IID_IHTMLElement > pElement (pDisp);
    _bstr_t strText;

    pElement->get_tagName(   &strText.GetBSTR() );  //检查 strText 值
    pElement->get_outerHTML( &strText.GetBSTR() );
  }

抱歉!评论已关闭.