---
title: "使用C++实现SDK之WebBrowser容器 系列的一个补充. 关于GetHtmlDocumentX()"
author: "helpbs"
date: "2011-12-31T09:54:00Z"
tags: []
slug: "c-sdk-webbrowser-gethtmldocumentx"
draft: false
lastmod: "2012-04-24T08:50:28Z"
id: 1495939
url: "https://helpbs.iteye.com/blog/1495939"
---

之前的文章 "[http://blog.csdn.net/norsd/archive/2008/09/13/2921389.aspx](http://blog.csdn.net/norsd/archive/2008/09/13/2921389.aspx)" 实现了一个WebBrowser.

但是万物总不是完美的, 最近有网友问,GetHTMLDocumentX 系列函数的实现,是否需要Release.

当时我回答不需要. 我是这样考虑的:

WebBrowser 类只提供一个(系列) IHtmlDocumentX* 指针, 在析构的时候 Release. 这样的实现听起来不错,实际运行也似乎没有问题.

非常巧合,最近终于发现问题.

考虑这样的情况:

1.打开页面 nothere.html

2.如果这个页面无法打开,WebBrowser会不断重试

3.这时候如果立刻跳转到其他页面,这时候WebBrowser会产生一个新的 IDocument 对象

这时候我们的 IHtmlDocumentX* 指针指向的还是之前的 nothere.html

只有我们 get\_Document 才能得到当前页面的 document.

所以代码应该改成这样:

[view plain](http://blog.csdn.net/norsd/article/details/4000478 "view plain")

01. IHTMLDocument2*
02. WebBrowser::GetHTMLDocument2()
03. {
04. if(\_pHtmlDoc2!=NULL)
05. \_pHtmlDoc2-&gt;Release();
06. \_pHtmlDoc2=NULL;
07. IWebBrowser2\*pWB2=NULL;
08. IDispatch\*pDp=NULL;
09. NULLTEST\_AE(pWB2=GetWebBrowser2());
10. HRTEST\_E(pWB2-&gt;get\_Document(&pDp));
11. NULLTEST\_E(pDp);//ie7情况下如果document还不存在,则pWB2-&gt;get\_Document会返回错误,但是ie6则不会有有任何HR错误,他只是使pDp=NULL.
12. HRTEST\_E(pDp-&gt;QueryInterface(IID\_IHTMLDocument2,(void\*\*)&\_pHtmlDoc2));
13. return\_pHtmlDoc2;
14. RETURN:
15. returnNULL;
16. }

p.s: IHTMLDcoumentX , 表示 IHTMLDocument , IHTMLDocument2 , and so on.