Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if JS has access to an iframe's document

Is there any standard way to know if my script has access to an iframe's document?

I couldn't find anything in the web so I came up with this:

function checkifr() {
    function errHandler() {
        alert('Error. Try again later.');
    }
    var ifr = $('#ifr')[0]; //the iframe DOM element

    try {
        var d = ifr.contentWindow || ifr.contentDocument;
        if (!d) {
            errHandler();
            return false;
        }

        var b = $('#ifr').contents().find('body');
        //... manipulate iframe content

    } catch(e) {
        errHandler();
    }
}

It works, Firefox throws an error when I try to access the iframe's contents and ends up in the catch block. Chrome shows an Unsafe JavaScript attempt to access frame warning in the console but never enters the catch block, it seems to return null for those attempts so the initial if (!d) takes care of it. Opera and IE behave similarly to FF. Edit: With the code above, now Chrome returns an "empty" Window object (with no properties) which do not trigger my if block. Check Esailija's answer which works nicely cross-browser!

Here's the fiddle.

I can't test the iframe's src against window.location.

Justificatory Background: This is because this function is part of a small image upload plugin which I'm developing (using an iframe as target since IE<9 doesn't support XHR2), and the goal is mainly validating connection error/timeout/etc. The default browser pages for these errors are subject to the same origin police, hence the purpose of this question. I don't want to send an ajax call to check if the page is available, as I want to validate the submit request itself. jQuery's .load handler doesn't fire for errors, jQuery's .error and the onerror HTML attribute do not work for this. An illustration of the working script is available here, but you may ignore it completely and simply answer the question below.

Note that the above block is solely for illustrating why I can't use the iframe.src.

I do think that there should an easier/standard way to check an iframe's "accessibleness", but I can't find anything in the web nor SO except half-solutions which simply check the iframe.src and do not apply for many cases. If my hackish try/catch block is considered a technically "clean" solution, others may re-use it if no better option is found.

So is there any standard or simpler way or jQuery plugin to check if my script has access to an iframe's document without comparing the iframe's src with the window.location? Without try/catch blocks and errors/warnings in the console if possible.

like image 644
Fabrício Matté Avatar asked Aug 08 '12 20:08

Fabrício Matté


People also ask

How can I tell if an iframe page is loaded?

In short, to check if a page is in an iframe, you need to compare the object's location with the window object's parent location. If they are equal, then the page is not in an iframe; otherwise, a page is in an iframe.

How do I check if a JavaScript frame is loaded?

To check if iframe is loaded or it has a content with JavaScript, we can set the iframe's onload property to a function that runs when the iframe is loaded. document. querySelector("iframe"). onload = () => { console.

How can I access iframe element with JavaScript?

Getting the element in Iframeconst iframe = document. getElementById("myIframe"); Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe.


1 Answers

Here's another option, can't really do it without try catch.

Tests http://jsfiddle.net/LHjwZ/11/

function checkIframe( ifr ) {
    var key = ( +new Date ) + "" + Math.random();

    try {
        var global = ifr.contentWindow;
        global[key] = "asd";
        return global[key] === "asd";
    }
    catch( e ) {
        return false;
    }
}
like image 135
Esailija Avatar answered Oct 05 '22 03:10

Esailija