2

It seem $watch not work with cookies expires. Here is the code I tried

 $scope.$watch(function(){
        return $cookies.get('cookies')
    },function(newVal,oldVal){
        if(!newVal){
            console.log('ok')

        }
    })

I can check it with $interval. But I dont want call digest cycle every 2s , or 5s.

3
  • $scope.watch will watch cookie much more frequently than every 2s or 5s Commented Jun 29, 2017 at 3:39
  • @harishr yes , but it seem it not work when I delete cookies , or cookies expired Commented Jun 29, 2017 at 3:58
  • Watch functions are only triggered if there is a digest cycle. If there is no digest cycle, the watch function will not execute and will not detect the expiration of the cookie. Use $interval which is guaranteed to initiate a digest cycle at the specified interval. Commented Jun 29, 2017 at 4:06

1 Answer 1

1

Unfortunately, it is not possible to read the cookie expiration time in JS so my first idea of iterating over them and executing action on their expiration dates is not possible.

If you don't want to start a digest on every "cookie check", you can disable invoking it with the fourth parameter for the $interval set to false. See the $interval docs.

Example code:

.run(function($cookies, $interval) {
  var previouslyAvailableCookies = Object.keys($cookies.getAll());
  var watchCookieChanges = function() {
     var availableCookies = Object.keys($cookies.getAll());
     var expiredCookies = previouslyAvailableCookies.filter(function(cookieName) { return availableCookies.indexOf(cookieName) < 0; });
     var newCookies = availableCookies.filter(function(cookieName) { return previouslyAvailableCookies.indexOf(cookieName) < 0; });
     if (expiredCookies.length || newCookies.length) {
       document.writeln("<p>New cookies: " + newCookies 
                      + "<br>Expired cookies: " + expiredCookies + '</p>');
     }
    previouslyAvailableCookies = availableCookies;
  };
  $interval(watchCookieChanges, 3000, 0, false);
})

And a codepen.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.