dark_shadow
dark_shadow

Reputation: 3573

How to close an authentication pop up window having a cross-domain url?

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>

Upvotes: 1

Views: 2437

Answers (1)

noseratio
noseratio

Reputation: 61744

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.

Upvotes: 1

Related Questions