Wednesday, 21 August 2013

JavaScript timing issue - window closing before sessionStorage values are set

JavaScript timing issue - window closing before sessionStorage values are set

We are putting together an FSSO API that requires a popup window for the
user to log in. In the popup, we perform two tasks:
Calling a service to populate a profile values, then setting a page to
redirect the user to based on the event type (login or registration).
Redirecting the user to the redirect page in the parent window and closing
the FSSO popup.
Code:
$(document).ready(function() {
var nextPage = "index.html",
storage = window.opener.sessionStorage;
function setStorage(callback){
$.ajax({
type: "GET",
cache: false,
dataType: "json",
url: "https://someserviceURL/service/profile",
success: function(objJSON){
//storage.op is set on the parent page when login
or reg link is clicked
if (storage.op == "login") {
storage.firstname = objJSON.firstName;
storage.lastname = objJSON.lastName;
storage.setItem('loggedIn',JSON.stringify(true));
//Some browsers don't support booleans in
sessionStorage
nextPage = "dashboard.html";
}
else if (storage.op == "register") {
storage.firstname = objJSON.firstName;
storage.lastname = objJSON.lastName;
storage.setItem('loggedIn',JSON.stringify(true));
nextPage = "options.html";
}
},
error: function( jqXHR, textStatus, errorThrown){
//display error message
}
});
callback();
}
setStorage(function(){
if (typeof window.opener != "undefined" && window.opener
!= null){
setTimeout(function(){
window.opener.location.href = nextPage;
window.close();
},3000);
}
});
});
Problem: The window seems to be closing before I'm able to set the
sessionStorage values if I set the timeout to anything less than 3000. I
just want to close the window in response to those values being set, not
some arbitrary amount of time passing. I tried the trick of setting the
timeout to 0 but no luck, and I tried just the callback with no timeout.
Looking for best practices here on handling timing issues like these, what
I have now feels hacky. :)

No comments:

Post a Comment