HappyNomad
HappyNomad

Reputation: 4548

IHTMLSelectionObject.createRange() throws UnauthorizedAccessException

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?

Upvotes: 4

Views: 1618

Answers (1)

Sheng Jiang 蒋晟
Sheng Jiang 蒋晟

Reputation: 15271

This is expected behavior, Cross-site scripting is disabled by default, and you are executing scripts across frames regardless their domains.

Upvotes: 1

Related Questions