Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can i be notified of cookie changes in client side javascript

Can I somehow follow changes to cookies (for my domain) in my client side javascript. For example a function that gets called if a cookie gets changed , deleted or added

In order of preference

  • standard cross browser
  • cross browser
  • browser specific
  • extension / plugin

Why? because cookies I depend on in window / tab #1 can get changed in window / tab #2.

I found out that chrome allows extensions to be notified of cookies changes. But thats my least favorite option

like image 619
pm100 Avatar asked Jan 15 '13 18:01

pm100


People also ask

Can cookies be accessed by client side?

Cookies can only be read by the website the domain that creates them; you can use sub-domains domains, url paths. Cookies are generally considered insecure if used from the client side, and should not be used to hold sensitive data if accessed from the client side.

Can JavaScript change cookies?

Change a Cookie with JavaScript With JavaScript, you can change a cookie the same way as you create it: document.

Can JavaScript read third party cookies?

For security reasons, the cookie is accepted only if the server is a member of the domain specified by the domain string. If foo.com sent a cookie which had the domain name of bar.com , or even .com , then JavaSCript code on bar.com could read that cookie.

Which command is used to create a new cookie on the client side in JavaScript?

This code defines a function, setCookie(). This function will create a cookie with the name “username”, value “Max Brown” with an expiration date of 30 days from the time it was created.


1 Answers

One option is to write a function that periodically checks the cookie for changes:

var checkCookie = function() {      var lastCookie = document.cookie; // 'static' memory between function calls      return function() {          var currentCookie = document.cookie;          if (currentCookie != lastCookie) {              // something useful like parse cookie, run a callback fn, etc.              lastCookie = currentCookie; // store latest cookie          }     }; }();  window.setInterval(checkCookie, 100); // run every 100 ms 
  • This example uses a closure for persistent memory. The outer function is executed immediately, returning the inner function, and creating a private scope.
  • window.setInterval
like image 192
calebds Avatar answered Sep 19 '22 08:09

calebds