IHTMLSelectionObject.createRange()抛出UnauthorizedAccessException

时间:2009-09-13 02:15:20

标签: .net internet-explorer dom webbrowser-control bho

我编写了以下代码,用于从当前网页中检索所选文本:

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()

如何避免此错误?

1 个答案:

答案 0 :(得分:1)

这是预期的行为,默认情况下禁用Cross-site scripting,并且您正在跨框架执行脚本,无论其域名如何。