Check if JS has access to an iframe's document Check if JS has access to an iframe's document jquery jquery

Check if JS has access to an iframe's document


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;    }}


Here's one idea that will work whether the accesses throw an exception or not:

function checkFrameAccess(ifr) {    try {        var doc = ifr.contentDocument || ifr.contentWindow.document;        var origClass = doc.body.className;        var newClass = origClass += " xxxxx";        doc.body.className = newClass;        var valid = doc.body.className == newClass;        doc.body.className = origClass;        return(valid);    } catch(e) {        return(false);    }}

If they throw an exception, you end up in the exception handler and return false. If they don't throw an exception, then you test whether you can actually modify the className of the body tag in the frame. If the modification works, then apparently, you could modify it. If not, then it wouldn't let you access it.