canAccessIFrame()

by jfriend00

HTML

<iframe id="remote" class="frame" src="http://www.the-friend-family.com"></iframe>
<iframe id="local" class="frame" src="http://fiddle.jshell.net/jfriend00/5esYG/show"></iframe>
<button onclick="testAccess()">Test</button>
<div id="result"></div>

CSS

.frame {
    width: 100%;
    height: 200px;
}

#result {
    font-family: "Courier New";
    margin-top: 20px;
}

JavaScript

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

function testAccess() {
    var remote = canAccessIFrame(document.getElementById("remote"));
    var local = canAccessIFrame(document.getElementById("local"));
    document.getElementById("result").innerHTML = 
        "Remote iframe canAccess: " + remote + "<br>" +
        "Local iframe canAccess: " + local;
}