firame标签: IHTMLElement -> IHTMLFrameBase2 -> IHTMLWindow2 -> IHTMLDocument2 跨域访问

获得iframe标签的元素指针

CComPtr<IHTMLElement> spAdIframe = ...

CComQIPtr<IHTMLFrameBase2> spFrameBase2 = spAdIframe;

CComPtr<IHTMLWindow2> spIframeWindow2 = NULL;
hr = spFrameBase2->get_contentWindow(&spIframeWindow2);

由此可得到iframe元素对应的IHTMLWindow2指针,然而如果直接使用IHTMLWindow2::get_document来获取IHTMLDocument2指针的话,经常得到的是E_ACCESSDENIED错误,因为iframe元素经常用于跨域的访问,即iframe内的文档来源src与其parent的src的hostname不同,但可以通过下面的方法绕过webbrowser的安全检查。

// Converts a IHTMLWindow2 object to a IHTMLDocument2. Returns NULL in case of failure.
// It takes into account accessing the DOM across frames loaded from different domains.
CComQIPtr<IHTMLDocument2> HtmlWindowToHtmlDocument(CComQIPtr<IHTMLWindow2> spWindow)
{
ATLASSERT(spWindow != NULL);

CComQIPtr<IHTMLDocument2> spDocument;
HRESULT hRes = spWindow->get_document(&spDocument);

if ((S_OK == hRes) && (spDocument != NULL))
{
// The html document was properly retrieved.
return spDocument;
}

// hRes could be E_ACCESSDENIED that means a security restriction that
// prevents scripting across frames that loads documents from different internet domains.
CComQIPtr<IWebBrowser2> spBrws = HtmlWindowToHtmlWebBrowser(spWindow);
if (spBrws == NULL)
{
return CComQIPtr<IHTMLDocument2>();
}

// Get the document object from the IWebBrowser2 object.
CComQIPtr<IDispatch> spDisp;
hRes = spBrws->get_Document(&spDisp);
spDocument = spDisp;

return spDocument;
}


// Converts a IHTMLWindow2 object to a IWebBrowser2. Returns NULL in case of failure.
CComQIPtr<IWebBrowser2> HtmlWindowToHtmlWebBrowser(CComQIPtr<IHTMLWindow2> spWindow)
{
	ATLASSERT(spWindow != NULL);

	CComQIPtr<IServiceProvider>   spServiceProvider = spWindow;
	if (spServiceProvider == NULL)
	{
		return CComQIPtr<IWebBrowser2>();
	}

	CComQIPtr<IWebBrowser2> spWebBrws;
	HRESULT hRes = spServiceProvider->QueryService(IID_IWebBrowserApp, IID_IWebBrowser2, (void**)&spWebBrws);
	if (hRes != S_OK)
	{
		return CComQIPtr<IWebBrowser2>();
	}

	return spWebBrws;
} 

  

 

附: 
IE(控件/接口)中主要有4个部分, Browser, Document, Frame/IFrame, Element , 其对应接口分别是 
Browser          -     IWebBrowser2
Document       -     IHTMLDocument2
Frame/IFrame-     IHTMLWindow2
Element          -     IHTMLElement
可以通过下面方法互相获取 
browser      -> document        IWebBrowser2::get_Document
document     -> frame           IHTMLDocument2::get_parentWindow
frame        -> document        IHTMLWindow2::get_document
frame        -> parent frame    IHTMLWindow2::get_parent
frame        -> children frames IHTMLWindow2::get_frames
element     -> Frame              IHTMLElement->QI(IHTMLFrameBase2) -> IHTMLFrameBase2->get_contentWindow -> IHTMLWindow2 ->
HtmlWindowToHtmlWebBrowser -> IWebBrowser2

参考:

http://shenan1984.blog.163.com/blog/static/2530851020109201042263/

 

 

 

你可能感兴趣的:(document)