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

后端 未结 8 1081
梦如初夏
梦如初夏 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:01

    use x-frame header this will prevent to load your site to frame/iframe . there are various options read here

    0 讨论(0)
  • 2020-12-05 14:03

    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.

    0 讨论(0)
  • 2020-12-05 14:06

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 14:13

    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.

    0 讨论(0)
  • 2020-12-05 14:22

    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>
    
    0 讨论(0)
提交回复
热议问题