簡體   English   中英

繞過同源政策,從跨域iframe中獲取網頁的頂級網址

[英]Get around same-origin policy to get top URL of a page from inside a cross-domain iframe

我在第三方網站上的iframe中運行了一些代碼。 有些將直接位於首頁,有些將位於另一個iframe中,其中一些可能是跨域的。 我需要找到一種方法來使用任何必要的方法獲取首頁的URL值。

由於跨域策略,我可以走得最遠,直到瀏覽器停止代碼正在執行的操作。 我抓住了錯誤並查看了我當前窗口上下文的引用者。大多數情況下,上面的頁面是首頁,但不一定。

我能看到的唯一方法是建立一個我認為是首頁的URL列表,然后發送一個帶有JS瀏覽器的機器人驗證,看看我的代碼是否達到了iframe實際上直接嵌套在它們中。

盡管如此,這仍然不是特別准確,我相信必須有另一種方式來做到這一點......

感謝任何能提供幫助的人。

實際上有一種方法可以在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中的代碼,請告訴我,或者只是通過在線轉換器運行它。

如果不與某種外部系統通信,絕對不可能。 收集數據的最干凈/最准確的方法是在瀏覽器允許的情況下獲取頂部窗口URL,但是捕獲錯誤並使用帶有標志的引用來注意它是引用者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM