How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

akshat picture akshat · Nov 28, 2008 · Viewed 334.5k times · Source

I am writing an iframe based facebook app. Now I want to use the same html page to render the normal website as well as the canvas page within facebook. I want to know if I can determine whether the page has been loaded inside the iframe or directly in the browser?

Answer

Greg picture Greg · Nov 28, 2008

Browsers can block access to window.top due to same origin policy. IE bugs also take place. Here's the working code:

function inIframe () {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}

top and self are both window objects (along with parent), so you're seeing if your window is the top window.