1

I need to delete a cookie when the a tab is closed, searching internet I found this:

$(window).unload(function() {
   $.cookies.del('myCookie');
});

This solution is not working, the cookie persist while the browser is running. there are more ways to achieve the deletion? I'm using the jquery-cookie plugin.

dimvcl
  • 289
  • 1
  • 3
  • 13

2 Answers2

1

My proposal is:

$(window).on('beforeunload', function(e) {
  document.cookie = 'Name of your cookie' + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
});

To remove cookie I prefer to set the expiration time.

gaetanoM
  • 41,594
  • 6
  • 42
  • 61
  • I closed the tab and return to the page and it the cookie remains active. – dimvcl Jan 06 '16 at 19:44
  • It's very strange because setting the expiration time in the past your cookie is no more valid✔ – gaetanoM Jan 06 '16 at 20:00
  • A cookie for Js can be valid or invalid. If you instead want to remove physically the cookie from the browser conf you need to write a browser extension that is the only way to use Js functions to reconfigure the cache of your browser. I hope this will satisfy your curiosity. – gaetanoM Jan 06 '16 at 20:20
  • I put: $(window).on('beforeunload', function(e) { return "Do you really want to close?"; }); and it show the dialog every time when I change the page not when I close the tab. – dimvcl Jan 06 '16 at 21:15
  • The event beforeunload is fired not only on tab close but also on form submit, anchor click and so on. If you want to handle these events and others you can create a global variable, set it to false when for instance a form is submitted the global variale can be set so that in the window event you can check this variable... Otherwise, like I already told you you need to act on browser extensions.... If this is the final question could you accept my answer? – gaetanoM Jan 06 '16 at 21:18
0

You should use window.onbeforeunload Event. See MDN

campino2k
  • 1,618
  • 1
  • 14
  • 25
  • 1
    I coded: window.addEventListener("beforeunload", function (event) { $.cookies.del('nav'); }); but it doesn't work. – dimvcl Jan 06 '16 at 19:11