且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何关闭具有跨网域网址的身份验证弹出窗口?

更新时间:2023-11-27 19:02:52

认为有一个很好的和通用的解决方案,这不同于你链接的答案。



一个愚蠢的尝试解决这可能是使用一个计时器,并轮询值 document.documentElement.innerHTML 用于子窗口及其所有子框架。



如果整个结构已稳定对于一个相当长的延时(即,没有更改HTML和没有异常抛出),它可能表明所有内部导航或XHR调用已完成,可以关闭窗口。


I was following the accepted answer for this question How do I get around window.opener cross-domain security to solve my problem. The code works great but fails at one use case where instead of the pop up window url getting changed from some other domain to your own domain, it simply redirects on its own domain just like sometime if you try to authenticate a third paty app on facebook or some other social network, it simply redirects on its own as you have already authenticated earlier. How can we handle this scenario in the following code:

<!DOCTYPE html>
<head>
<title>main</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<script>
window.addEventListener("message", function(ev) {
    if (ev.data.message === "deliverResult") {
        alert("result: " + ev.data.result);
        ev.source.close();
    }
});

function Go() {
    var child = window.open("child.html", "_blank", "height=200,width=200");

    var leftDomain = false;
    var interval = setInterval(function() {
        try {
            if (child.document.domain === document.domain)
            {
                if (leftDomain && child.document.readyState === "complete")
                {
                    // we're here when the child window returned to our domain
                    clearInterval(interval);
                    alert("returned: " + child.document.URL);
                    child.postMessage({ message: "requestResult" }, "*");
                }
            }
            else {
                // this code should never be reached, 
                // as the x-site security check throws
                // but just in case
                leftDomain = true;
            }
        }
        catch(e) {
            // we're here when the child window has been navigated away or closed
            if (child.closed) {
                clearInterval(interval);
                alert("closed");
                return; 
            }
            // navigated to another domain  
            leftDomain = true;
        }
    }, 500);
}
</script>
</head>
<body>
<button onclick="Go()">Go</button>
</body>

Taking your comments into account, I don't think there's an nice and universal solution to this, unlike with the answer you linked.

A dumb attempt at solving this might be to use a timer and poll the value document.documentElement.innerHTML, for the child window and its all sub-frames.

If the whole structure has been steady for a reasonably long time-lapse (i.e., no changes in HTML and no exceptions thrown), it might be an indication that all internal navigation or XHR calls have been completed, and it's OK to close the window.