Search code examples
javascripthtmliframecross-browser

Foolproof way to detect if this page is INSIDE a cross-domain iframe


An answer to "Foolproof way to detect if iframe is cross domain" describes a method to test if an iframe on a page points to a same-domain or cross-domain page, working around different browsers' interpretations of the cross-domain policy and avoiding error messages that would interrupt a user or stop javascript.

I'm looking to do the equivalent of this but from the child page inside the iframe testing whether it is inside a cross-domain iframe or not.

It's possible to access (same domain) info about the parent with the parent global e.g. parent.document.location, but is there a reliable way to do this cross-browser without crashing into errors when it detects that the parent is cross-domain?


For handy testing, here's a jsbin inside a jsfiddle that crashes into an error when trying to test if parent.location.host is accessible. Is there a reliable way to get something usable like false telling us that this is a cross-domain parent, instead of an error?

Is there a try...catch variant which will be robust cross-browser? Or maybe some clever trick using a return value from parent.postMessage()? (although the parent page cannot be edited)


Use case: imagine embedable content that is to be embedded on pages on its own site, and by third parties. If the page is on a same-domain iframe, we hide branding and links back to the original site because the user is already here. If they access the page from a 3rd party iframe or load the page directly, we show the branding and credits so they can see the source of the content.


To clarify, I know about the same-domain policy and I don't care what the cross browser domain is, I'm just looking to write a simple but reliable if condition like if( crossDomainParent() ){ /* do something */}


Solution

  • First check if you are IFramed.

    window.self !== window.top
    

    If you are IFramed, then your referrer is your parent frame url.

    document.referrer
    

    From this url you should be able to detect if you want to branch your code.