Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if an iframe is accessible without triggering an error?

Basically I have an iframe loaded that is accessed from the parent whenever it trigger the onload event. It works fine but I'm getting errors when the contents of the iframe are no longer on the same domain, which is to be expected.

Only thing is, I'd like to suppress these errors. Unfortunately a try/catch doesn't catch this exception and trying to access any of these properties to validate them produces the same error again, thus defeating the purpose.

Is there a reliable way for me to simply check if the iframe contents are accessible without producing any error messages?

Thanks

Edit:

For the sake of context and not having people answer with irrelevant comments; I am writing a small script that auto resizes the iframe on the parent page based on the height of the iframes document. When a user clicks a link inside the iframe that points outside the domain I obviously won't be able to detect the height of the page, but I'd prefer not to trigger any errors in the console and instead handle the exception gracefully.

I am aware that there are workarounds available, I am simply trying to educate myself by figuring out if there is a graceful way to handle these kinds of cases, rather than just resorting to an ugly workaround.

like image 578
Naatan Avatar asked Jan 18 '12 21:01

Naatan


2 Answers

Try this:

var $frame = $("#frameId"); // swap with the id of the iframe
try {
    var canAccess = $frame.contents();
    if(!!canAccess) {
       // same domain yay you have access
       // do your thing here
    }
}
catch( e ) {
    // bummer can't do much with it
    return false;
}

EDIT: add a try and catch, no error will return false.

like image 92
Ady Ngom Avatar answered Sep 27 '22 22:09

Ady Ngom


The jQuery approach can also be done with regular JS:

function iframe_accessible(theiframe) {
  var thedoc, debug=true;
  try{
    thedoc = (theiframe.contentWindow || theiframe.contentDocument);
    if (thedoc.document)
        thedoc = thedoc.document;
    if (debug)
        console.log('Accessible');
    return true;
  }
  catch(err) {
    if (debug)
        console.log("Not accessible because of\n" + err);
    return false;
  }
}

var elm = document.querySelector('iframe'); // If it exists, of course
console.log(iframe_accessible(elm));
like image 30
LWC Avatar answered Sep 27 '22 23:09

LWC