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 ar
use x-frame header this will prevent to load your site to frame/iframe . there are various options read here
With your current restrictions, there's no way to achieve this using the DOM API. Any evaluation with a window that belongs to another domain will spew out an error.
However, a "hack" would be to send an XHR from your child window to load a known page in your domain. If this XHR completes successfully, then you know that both windows are the same domain.
However, this will log an error message to the console.
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.
I attempted to use referer to determine cross-domain, but I discovered it was unreliable on many sites. Maybe someone will find this useful.
function IsCrossDomainFrame() {
if( parent === window ) return false; //not a frame
var parentLocation = new URL(document.referer);//the referer of an iframe is the parent
return (parentLocation.protocol !== location.protocol ||
parentLocation.hostname !== location.hostname ||
parentLocation.port !== location.port);
}
Protocol, hostname, and port determine cross-domain.
If I see your use case:
I would check it server side (who called your site), using $_SERVER['REMOTE_ADDR']
, and if it is your IP than you can hide branding and links backs.
If the use case is about to prevent framing your site you can use X-Frame-Options: deny
.
Other guess:
Elements inside a document have a ownerDocument
property, maybe that can help detecting what you want.
Try this (in iframe)
<script type="text/javascript">
var detectOrigin = (window.location.ancestorOrigins === undefined ?
/example.com/.test(document.domain) /* firefox */ :
/example.com/.test(window.location.ancestorOrigins[0])); /* webkit */
if (detectOrigin === true) {console.log(detectOrigin)}; /* `true` example.com origin */
if (detectOrigin === false) {console.log(detectOrigin)}; /* `false` !example.com origin */
</script>