title: Foolproof way to detect if iframe is cross domain
body: <p>I'm trying to determine if any iframe is cross-domain or not. According to the accepted answer in this question: <a href="https://stackoverflow.com/questions/2365822/detect-when-iframe-is-cross-domain-then-bust-out-of-it">Detect when iframe is cross-domain, then bust out of it</a> it says to put the code accessing the <code>contentDocument</code> of the iframe in a <code>try / catch</code> block. I tried this for a cross-domain iframe in Chrome:</p>
  
  <pre><code>try { 
    document.getElementsByTagName('iframe')[0].contentDocument;
  } catch(err){
    console.log("called");
  }
  </code></pre>
  
  <p>and it still throws the cross-domain error and does not catch the error.</p>
  
  <p>I also tried to check if the protocol + host + port of the parent page url is in the <code>src</code> of the iframe:</p>
  
  <pre><code>function thirdPartyIframe(iframe){
    var url = document.location.protocol + "//" + document.location.hostname + (document.location.port === "" ? "" : ":" + document.location.port);
    var regexp = new RegExp(url.replace(/\//g, "\\/").replace(/\./g, "\\."));
    if (iframe.src === '' || regexp.test(iframe.src)){
      return false;
    } else {
      return true;
    }
  }
  </code></pre>
  
  <p>but this does not seem to work for the first iframe on the homepage of Facebook with <code>src</code> equal to (it's long):</p>
  
  <pre><code>"http://www.facebook.com/ai.php?aed=AQLlH2cfdnsnLrDUVyqrQPlWpayw9N09Z_iNuhulevbeEfVa4mcVRcT8cjAZOjQb8y1QXab5Ae3aSEJx49U_Qv35rtSp1VC9cY0_CrpOjMDk40hS_Xm57A996YtRVCcWSuRZ_jZERQ_iA_E4621NAbKHT9dsB7uElkRtTvl5K-zPI0jeH-BEnlZIOXbeEdbRC6qCwoToaltolpe-Ot2KWgkfb_vBZYpzUc3jQoEHzLG6tauO9l_hkXpYpHxnt-KYFKIFZ1PgmrHgb0UcGjeKHl7yBR1AbW2n5XgdgaAhFvBjs5GZlKy566nvl8eLRA60orwkwtWYeN8-gKoAmOLm7-6minsWn8lk1h2Qn3p07HCTSnYHfv1aJ6mF5jmuzP0YYe7Ym9ZbmK-tvax4uPAQJ2OdULilKbEh8M-2V9pVY3AC228OPlrRullZuuOg8DI2A8WeMF-fbbOdOFFVCe5Gj1CaZu3LYXiqdG7mUgY6AEpk9ZzGT4fC2K8DInQo1AypCvzG64C_bEWfODeXe0aGbkWwsUUmO7E5HFg0tvZkK5IAR_xxxQ2rlf5jbcEDo_2gdIDdHe1HT75-SJLUsSA0M8EU01oNNPuWwEC2BW6inepc9QPuqeg42tcEbKLU-rIUnXDBLvgutft8azWPPQ6_LafGjCAmC9uTalagoWLLDMpQOThvPg7YeVd7qg_c9Mzn2GAfuswcxDSxyRIZo9MaOhA6mhfXeE1tmjyBBsMxnx08tO21Jsfgch59fmMxpeJzdsNMPK3FAojfglvCQ2Zrt_6ataexUB4xlM7_PhKrfBPtxb5fe2TE9-nlWruNEpoCrzI05yv4Go3CYEWHob06K_9iICfNVTFkSYGTiJnMXCy_fdgfyzUIn5QJIPRo4-Wnyg444zKAO_nyFW59LqbIanHVfFY6ybiA6KeC3meREWzTPSsrU5d_NbYHlJWb8uPNDR04jaH5e2qiYj3Y8qgLQA5m"
  </code></pre>
  
  <p>My function classifies it as not a third party iframe, but Chrome still throws the cross-domain error when I access its <code>contentDocument</code>.</p>
  
  <p>I'm looking for a foolproof, cross-browser way to do this.</p>