动态改变网页内容(CHtmlView/CWebBrowser2/IE

来源:百度文库 编辑:神马文学网 时间:2024/04/30 02:57:35
很多时候,我们需要动态的修改网页的内容。
早先COM集中营曾有篇文章介绍过,源代码:http://263.csdn.net/FileBBS/files/2001_9/T_642_1.zip
其中基本代码如下:
void CMainFrame::OnChangehtml()
{
IHTMLDocument2 *pHTMLDocument=NULL;
IPersistStreamInit *pPSI=NULL;
IStream *pStream=NULL;
HGLOBAL  hHTMLText;
if (!(pHTMLDocument = (IHTMLDocument2*)m_pHtmlView->m_browser.GetDocument()))//m_pHtmlView是CHtmlView或者WebBrowser
return;
if (FAILED(pHTMLDocument->QueryInterface(&pPSI)))
{
return;
}
pHTMLDocument->clear();
pPSI->InitNew();
LPCTSTR strText = m_pSourceView->LockBuffer();
DWORD dwLength= strlen(strText);
hHTMLText = GlobalAlloc(GMEM_FIXED, dwLength);
memset(hHTMLText, 0, dwLength);
memcpy(hHTMLText, strText, dwLength);
m_pSourceView->UnlockBuffer();
CreateStreamOnHGlobal(hHTMLText, TRUE, &pStream);
ULARGE_INTEGER libNewSize;
libNewSize.QuadPart = dwLength;
pStream->SetSize(libNewSize);
pPSI->Load(pStream);
pStream->Release();
pPSI->Release();
}
网页内容倒是动态改变了,但你查看一下网页属性会发现,网页变成了:about:blank
很痛苦是吧,变成空白页了,呵呵~~
下面方法利用IHtmlDocument2的方法动态改变网页内容,而不改变网页属性
BOOL CXXXXView::put_bodyHtml(CString cs)
{
IHTMLDocument2* pHtmlDoc2 = (IHTMLDocument2*)GetHtmlDocument();
if( pHtmlDoc2)
{
HRESULT hr = S_OK;
IHTMLElement *pBodyElement;
hr=pHtmlDoc2->get_body( &pBodyElement);
if(pBodyElement!=NULL)
{
BSTR pbBody = cs.AllocSysString();
hr=pBodyElement->put_innerHTML(pbBody);   //类似的还有put_innerTEXT
pBodyElement->Release();
}
pHtmlDoc2->Release();
if( hr==S_FALSE) return FALSE;
else return TRUE;
}
else return FALSE;
}
到时候你只需要这样调用:put_BodyHtml("a string");