IHTMLSelectionObject.createRange() 抛出 UnauthorizedAccessException
我编写了以下代码来从当前网页检索所选文本:
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()
如何避免此错误?
I wrote the following code for retrieving the selected text from the current webpage:
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;
But on certain webpages, the call to frameDoc.selection.createRange() throws an UnauthorizedAccessException:
System.UnauthorizedAccessException was unhandled Message="Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))" Source="Microsoft.mshtml" StackTrace: at mshtml.IHTMLSelectionObject.createRange()
How can I avoid this error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是预期行为,默认情况下跨站点脚本处于禁用状态,并且您正在执行脚本跨框架,无论其域。
This is expected behavior, Cross-site scripting is disabled by default, and you are executing scripts across frames regardless their domains.