Get current URL from IFRAME

前端 未结 7 1388
小鲜肉
小鲜肉 2020-11-22 08:08

Is there a simple way to get the current URL from an iframe?

The viewer would going through multiple sites. I\'m guessing I would be using something in javascript.<

7条回答
  •  名媛妹妹
    2020-11-22 08:50

    If you're inside an iframe that don't have cross domain src, or src is empty:

    Then:

    function getOriginUrl() {
        var href = document.location.href;
        var referrer = document.referrer;
        // Check if window.frameElement not null
        if(window.frameElement) {
            href = window.frameElement.ownerDocument.location.href;
            // This one will be origin
            if(window.frameElement.ownerDocument.referrer != "") {
                referrer = window.frameElement.ownerDocument.referrer;
            }
        }
        // Compare if href not equal to referrer
        if(href != referrer) {
            // Take referrer as origin
            return referrer;
        } else {
            // Take href
            return href
        }
    }
    

    If you're inside an iframe with cross domain src:

    Then:

    function getOriginUrl() {
        var href = document.location.href;
        var referrer = document.referrer;
        // Detect if you're inside an iframe
        if(window.parent != window) {
            // Take referrer as origin
            return referrer;
        } else {
            // Take href
            return href;
        }
    }
    

提交回复
热议问题