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

后端 未结 8 1084
梦如初夏
梦如初夏 2020-12-05 13:37

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

8条回答
  •  北海茫月
    2020-12-05 14:09

    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.

提交回复
热议问题