编程语言
首页 > 编程语言> > javascript-多个嵌套的跨域iFrame内部的顶部窗口的URL形式

javascript-多个嵌套的跨域iFrame内部的顶部窗口的URL形式

作者:互联网

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

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

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

var parentUrl = document.referrer;

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

至少在某些现代浏览器中,是否可以在多个嵌套的跨域iFrame中标识顶部窗口的URL形式?

解决方法:

在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中的代码,请告诉我,或者直接通过转换器在线运行.

标签:cross-domain,iframe,cross-browser,javascript
来源: https://codeday.me/bug/20191030/1971781.html