1

I'm implementing external OAuth authentication at my webiste. On button click I'm opening popup with let's facebook auth page. Now I need to know when authentication is completed to read an OAuth token and close the popup.

click: function () {
   var popup = window.open(url, title, '<options>');
   popup.onload = function () {
       //1. if url contains token - finish OAuth authentication
       //2. close popup

       //but 'onload' doesn't work for external domains
   }
   return false;
},

When I'm trying to access using polling technique I'm hetting the following security error:

Uncaught SecurityError: Blocked a frame with origin "https://some_app_host_not_the_same_as_following.com" from accessing a frame with origin "https://some_auth_host_which_works_with_facebook.com". Protocols, domains, and ports must match.

How can I achieve this?

Mando
  • 11,414
  • 17
  • 86
  • 167
  • possible duplicate of [is it possible to open a popup with javascript and then detect when the user closes it?](http://stackoverflow.com/questions/3291712/is-it-possible-to-open-a-popup-with-javascript-and-then-detect-when-the-user-clo) – rfornal Dec 06 '14 at 02:33

1 Answers1

2

If you have control over the contents of the pop-up, handle the window's unload event there and notify the original window via the opener property, checking first whether the opener has been closed. Note this won't always work in Opera.

window.onunload = function() {
    var win = window.opener;
    if (win.closed) {
        win.someFunctionToCallWhenPopUpCloses();
    }
};

Since the unload event will fire whenever the user navigates away from the page in the pop-up and not just when the window is closed, you should check that the pop-up has actually closed in someFunctionToCallWhenPopUpCloses:

var popUp = window.open("popup.html", "thePopUp", "");
function someFunctionToCallWhenPopUpCloses() {
    window.setTimeout(function() {
        if (popUp.closed) {
            alert("Pop-up definitely closed");
        }
    }, 1);
}

If you don't have control over the contents of the pop-up, or if one of your target browsers does not support the unload event, you're reduced to some kind of polling solution in the main window. Adjust interval to suit.

var win = window.open("popup.html", "thePopUp", "");
var pollTimer = window.setInterval(function() {
    if (win.closed !== false) { // !== is required for compatibility with Opera
        window.clearInterval(pollTimer);
        someFunctionToCallWhenPopUpCloses();
    }
}, 200);
rfornal
  • 5,072
  • 5
  • 30
  • 42
  • I already implemented polling solution and unfortunately was unable to read the location property of the opened popup. Access Denied error :/ – Mando Dec 06 '14 at 03:23