Is there a client-side way to detect X-Frame-Options?

Newtang picture Newtang · Oct 31, 2011 · Viewed 21.8k times · Source

Is there any good way to detect when a page isn't going to display in a frame because of the X-Frame-Options header? I know I can request the page serverside and look for the header, but I was curious if the browser has any mechanism for catching this error.

Answer

Iftach picture Iftach · Feb 18, 2014

OK, this one is old but still relevant.

Fact: When an iframe loads a url which is blocked by a X-Frame-Options the loading time is very short.

Hack: So if the onload occurs immediately I know it's probably a X-Frame-Options issue.

Disclaimer: This is probably one of the 'hackiest' code I've written, so don't expect much:

var timepast=false; 
var iframe = document.createElement("iframe");

iframe.style.cssText = "position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;";
iframe.src = "http://pix.do"; // This will work
//iframe.src = "http://google.com"; // This won't work
iframe.id = "theFrame";

// If more then 500ms past that means a page is loading inside the iFrame
setTimeout(function() {
    timepast = true;
},500);

if (iframe.attachEvent){
    iframe.attachEvent("onload", function(){
    if(timepast) {
            console.log("It's PROBABLY OK");
        }
        else {
            console.log("It's PROBABLY NOT OK");
        }
    });
} 
else {
    iframe.onload = function(){
        if(timepast) {
            console.log("It's PROBABLY OK");
        }
        else {
            console.log("It's PROBABLY NOT OK");
        }
    };
}
document.body.appendChild(iframe);