Search code examples
javascriptangularjscookiessafarimobile-safari

$cookies.get() gives undefined although document.cookie contains the value


In the following code, xsrfCookie is sometimes undefined. I've measured it at about 20% of the calls.

This only seems to happen in MacOS Safari and on iOS in Safari en Chrome. I am using Angular 1.5.6.

$http.get('some_url')
  .success(function() {
    var xsrfCookie = $cookies.get('XSRF-TOKEN');
  });

Setting a breakpoint before or after xsrfCookie and logging document.cookie or even $cookies.get('XSRF-TOKEN') consistently shows the expected XSRF token.

I can only imagine this has something to do with the XSRF token from the GET being set asynchronously, in parallel to the success function, but I can't find anything in the angular.get() code that would suggest this.

Is there anyone who has run into this issue?


Solution

  • So far I have solved this by wrapping the retrieval of the cookie in a timeout:

    $http.get('some_url')
      .success(function() {
        $timeout(function() {
          var xsrfCookie = $cookies.get('XSRF-TOKEN');
        }, 1);
      });
    

    Unfortunately, I've not been able to find why this would be needed (expect that it might have something to do with the AngularJS 1.5 digest cycle) but I did found out some other things:

    • The original problem only occurs in Safari on iOS and MacOS, and only some of the time. Depending on the environment (intranet, internet) but also varying from day to day, I had sometimes a 100% failure rate and it would sometimes be as low as 10%.
    • If I log document.cookie as the first thing in the success callback, it is also empty (again only in Safari and only sometimes)
    • It might be that $timeout is only triggered after the digest is finished and even $timeout without the milliseconds param would work
    • There are hooks like onInit that would only run after the digest cycle is complete, but this call is several service calls deep and I do not understand how this would be involved.