Access parent URL from iframe

后端 未结 16 1545
野性不改
野性不改 2020-11-22 10:00

Okay, I have a page on and on this page I have an iframe. What I need to do is on the iframe page, find out what the URL of the main page is.

I have searched aroun

16条回答
  •  温柔的废话
    2020-11-22 10:23

    Yes, accessing parent page's URL is not allowed if the iframe and the main page are not in the same (sub)domain. However, if you just need the URL of the main page (i.e. the browser URL), you can try this:

    var url = (window.location != window.parent.location)
                ? document.referrer
                : document.location.href;
    

    Note:

    window.parent.location is allowed; it avoids the security error in the OP, which is caused by accessing the href property: window.parent.location.href causes "Blocked a frame with origin..."

    document.referrer refers to "the URI of the page that linked to this page." This may not return the containing document if some other source is what determined the iframe location, for example:

    • Container iframe @ Domain 1
    • Sends child iframe to Domain 2
    • But in the child iframe... Domain 2 redirects to Domain 3 (i.e. for authentication, maybe SAML), and then Domain 3 directs back to Domain 2 (i.e. via form submission(), a standard SAML technique)
    • For the child iframe the document.referrer will be Domain 3, not the containing Domain 1

    document.location refers to "a Location object, which contains information about the URL of the document"; presumably the current document, that is, the iframe currently open. When window.location === window.parent.location, then the iframe's href is the same as the containing parent's href.

提交回复
热议问题