我编写了以下代码,用于从当前网页中检索所选文本:
IHTMLDocument2 mainDoc = ... for ( int i = 0; i < mainDoc.frames.length; i++ ) { object refIndex = i; var frame = (IHTMLWindow2)mainDoc.frames.item( ref refIndex ); IHTMLDocument2 frameDoc; try { frameDoc = frame.document; } catch ( UnauthorizedAccessException ex ) { // Source: http://codecentrix.blogspot.com/2008/02/when-ihtmlwindow2document-throws.html var sp = (IServiceProvider)frame; // Use IServiceProvider.QueryService to get IWebBrowser2 object. object brws = null; sp.QueryService( ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out brws ); // Get the document from IWebBrowser2. IWebBrowser2 browser = (IWebBrowser2)brws; frameDoc = (IHTMLDocument2)browser.Document; } var range = frameDoc.selection.createRange() as IHTMLTxtRange; if ( !string.IsNullOrEmpty(range.text) ) return range.text; } return string.Empty;
但是在某些网页上,对frameDoc.selection.createRange()的调用会抛出UnauthorizedAccessException:
System.UnauthorizedAccessException was unhandled Message="Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))" Source="Microsoft.mshtml" StackTrace: at mshtml.IHTMLSelectionObject.createRange()
如何避免此错误?