Foolproof way to detect if iframe is cross domain

A more shorter and more readable function for modern browsers

function canAccessIframe(iframe) {
  try {
    return Boolean(iframe.contentDocument);
  }
  catch(e){
    return false;
  }
}

Tested with Chrome 79 and Firefox 52 ESR.

Explanation: you can check any iframe property that is not accessible cross-origin and convert to boolean. example: contentDocument / contentWindow.document / location.href / etc.

Boolean docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean


You need to do a little more than what's in your try/catch to handle different browsers and to handle different ways that browsers deal with cross domain access:

function canAccessIFrame(iframe) {
    var html = null;
    try { 
      // deal with older browsers
      var doc = iframe.contentDocument || iframe.contentWindow.document;
      html = doc.body.innerHTML;
    } catch(err){
      // do nothing
    }

    return(html !== null);
}

In your example, this would be:

var accessAllowed = canAccessIFrame(document.getElementsByTagName('iframe')[0]);

Working demo: http://jsfiddle.net/jfriend00/XsPL6/

Tested in Chrome 21, Safari 5.1, Firefox 14, IE7, IE8, IE9.