js检查该位置是否在我的跨域站点中

Js check if the location is in my site with cross domain

我有一个链接到其他网站的 iframe,当用户按下按钮时,iframe 内会重定向到我的网站。 我现在正在检查该位置是否是我的地址和做某事的基地。问题是,当位置仍然是另一个域时,我得到跨域错误:

Uncaught SecurityError: Blocked a frame with origin "http://localhost" from accessing a frame with origin "https://somesite.com".  The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "https". Protocols must match.

我如何解决这个错误?

document.getElementById("paymentIframe").addEventListener('load', function() {

var url = document.getElementById("paymentIframe").contentWindow.location.href;

 if( url.indexOf('status') > -1 && url.indexOf('success') > -1 )
             //i am in my domain   
 });

捕获错误并在 setTimeout(..., 10) 后重试可能是最简单的方法,直到错误不再发生(可能有上限;例如,如果您继续尝试超过 30 秒,请放弃)。

例如:

function checkForFrame(callback) {
    var timeout = Date.now() + 30000; // 30 seconds

    doCheck();

    function doCheck() {
        var url;

        try {
            url = document.getElementById("paymentIframe").contentWindow.location.href;
            if (url.indexOf('status') > -1 && url.indexOf('success') > -1)
                callback(true);
                return;
            }
        }
        catch (e) {
        }

        // The frame is inaccessible or the URL doesn't match; time out?
        if (Date.now() > timeout) {
            // Yup
            callback(false);
        } else {
            // Nope, try again in 10ms
            setTimeout(doCheck, 10);
        }
    }
}