顶部窗口的URL表单位于多个嵌套的跨域iFrame中

时间:2013-05-02 10:05:09

标签: javascript iframe cross-browser cross-domain

我的内容(包括JS)在iFrame中提供,然后将其封装在中间人(分销商)iFrame中,然后由发布者加载到他的网站中。所有3个帧都来自不同的域(跨域)。

我需要在iFrame中识别顶部框架(网站的网址)的网址。但我只能在我的iFrame中执行我的JS,中间人或网站发布者是非附属的,我不能要求他们放任何脚本或以任何方式修改中间iFrame或网站的源代码。

我的问题与this类似,答案是:

var parentUrl = document.referrer;

现在除了现在有2个嵌套的iFrame,所以如果我要求document.referrer,我只会获得中间人的iFrame的URL,而不是发布者的网站。

对于至少一些现代浏览器来说,可以在多个嵌套的跨域iFrame中识别顶部窗口的URL表单吗?

1 个答案:

答案 0 :(得分:4)

在Chrome和Opera中有一种隐秘的方式来获取域名(在多个嵌套的跨域iframe中),尽管在其他浏览器中无法实现。

你需要使用'window.location.ancestorOrigins'属性,这似乎是广告界的一个小商业秘密。他们可能不喜欢我发布它,但我认为对我们来说分享可能有助于他人的信息非常重要,理想情况下可以分享记录良好且维护良好的代码示例。

因此,我在下面创建了一段代码以供分享,如果您认为可以改进代码或评论,请不要犹豫,编辑Github上的要点,以便我们能够做得更好:

要点:https://gist.github.com/ocundale/281f98a36a05c183ff3f.js

代码(ES2015):

// return topmost browser window of current window & boolean to say if cross-domain exception occurred
const getClosestTop = () => {
    let oFrame  = window,
        bException = false;

    try {
        while (oFrame.parent.document !== oFrame.document) {
            if (oFrame.parent.document) {
                oFrame = oFrame.parent;
            } else {
                //chrome/ff set exception here
                bException = true;
                break;
            }
        }
    } catch(e){
        // Safari needs try/catch so sets exception here
        bException = true;
    }

    return {
        'topFrame': oFrame,
        'err': bException
    };
};

// get best page URL using info from getClosestTop
const getBestPageUrl = ({err:crossDomainError, topFrame}) => {
    let sBestPageUrl = '';

    if (!crossDomainError) {
        // easy case- we can get top frame location
        sBestPageUrl = topFrame.location.href;
    } else {
        try {
            try {
                // If friendly iframe
                sBestPageUrl = window.top.location.href;
            } catch (e) {
                //If chrome use ancestor origin array
                let aOrigins = window.location.ancestorOrigins;
                //Get last origin which is top-domain (chrome only):
                sBestPageUrl = aOrigins[aOrigins.length - 1];
            }
        } catch (e) {
            sBestPageUrl = topFrame.document.referrer;
        }
    }

    return sBestPageUrl;
};

// To get page URL, simply run following within an iframe on the page:
const TOPFRAMEOBJ = getClosestTop();
const PAGE_URL = getBestPageUrl(TOPFRAMEOBJ);

如果有人想要标准ES5中的代码,请告诉我,或者只是通过在线转换器运行它。