jeudi 12 février 2015

Is deleting a cookie in Javascript Synchronous?


I have more or less a duplicate of Javascript Delete Cookie Before Reload or Redirect which never got any answers.


I inherited some javascript code that does the following



function delete_cookie ( cookie_name )
{
var cookie_date = new Date ( ); // current date & time
cookie_date.setTime ( cookie_date.getTime() - 1 );
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}
delete_cookie ( "sessionId" );
window.location ="https://some_redirect";


The problem is that the GET for the redirect page contains the original cookie (which apparently was not deleted), and the server just continually responds with the delete/redirect code (tested on chrome/canary/IE). If it makes a difference, the cookie was initially set to simply "sessionId=;"


The cookie is always set with the following pattern



"Set-Cookie: sessionId=%s;path=/;%s postId=%s;%s " "\r\n"


I am aware that toGMTString is deprecated, and that setting directly to window.location is perhaps non-ideal. Neither of those seem related to the problem.


If I put the window.location call inside a setTimeout, or if I execute it as a callback from delete_cookie then everything magically works perfectly. But why?


This seems to work reliably



function delete_cookie (cookie_name, callback)
{
...
callback();
}
delete_cookie( "sessionID", doRedirect);


where doRedirect is just the window.location


Is this behavior expected? My presumption was that when the cookie was set with an expiry date in the past it would be deleted before code execution continued. Is there a better mechanism to ensure the cookie has been deleted prior to the redirection?


EDIT: Additional information


Modifying the cookie as follows doesn't help things



function delete_cookie ( cookie_name )
{
+ var retries = 0;
var cookie_date = new Date ( ); // current date & time
cookie_date.setTime ( cookie_date.getTime() - 1 );
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
+
+ while (document.cookie.indexOf("sessionId=") != -1)
+ {
+ retries +=1;
+ if (retries == 1000)
+ {
+ console.log("giving up after 1000 retries");
+ break;
+ }
+
+ }
+ console.log("We had to retry "+retries+" time(s)");
}
delete_cookie ( "sessionId" );


Console output is



giving up after 1000 retries


We had to retry 1000 time(s)



Interestingly, if I am debugging on the client I see the following


Canary (Version 42.0.2302.2 canary (64-bit))


After the javascript redirect code is served up from the dev console "Resources" tab, under Cookies->10.0.11.118 it says "This site has no cookies."


But in a separate tab to chrome://settings/cookies I can still see



Name: sessionId
Content:
Domain: 10.0.11.118
Path: /
Send for: Any kind of connection
Accessible to script: Yes
Created: Thursday, February 12, 2015 at 12:26:07 PM
Expires: When the browsing session ends




Aucun commentaire:

Enregistrer un commentaire