0

I want to clear localstorage cookies while tab or browser closing time.I don't want to clear 'cookies' while reload time.

I tried with unload and onbeforeunload events,both are not working in also If I use unload,it will fire even If I reload my application,so I don't want to use that.

finally what I want,clear cookies while tab or browser closing time.How can I do this.

Thanks,can anyone help me.

vasan
  • 2,203
  • 3
  • 18
  • 22
  • 1
    What is "localstorage cookies"? Is it [localstorage](http://diveintohtml5.info/storage.html) or is it [cookies](http://en.wikipedia.org/wiki/HTTP_cookie)? Usually a session cookie would do the trick here. It lives until the browser is closed. – spender Jun 23 '14 at 14:29
  • even when you can solve this problem, I think there will be another problem, such as what if user copies the URL of the current page and open a duplicated page, so closing 1 page will clear the cookie, which may cause the remaining page unusable (because the cookie has been cleared). – King King Jun 23 '14 at 14:30

2 Answers2

0

To get better support for the onunload event you can use the jQuery variant. Correct me if I'm wrong but the vanilla JavaScript onunload event is not supported in Chrome.

$( window ).unload(function() {
    // Clear localstorage & cookies
});

From the jQuery API Docs:

The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

LosBeekos
  • 76
  • 4
  • from what you explained, this would not be the solution because the OP wants some event triggered ***only*** when the tab/browser is closed. – King King Jun 23 '14 at 14:34
  • Yeah I know, but this would be the only way to do it in javascript. The only extra thing this would cause is that it would trigger the event when a user types in another URL, but its almost the same as if the user closed the tab or browser. – LosBeekos Jun 23 '14 at 14:38
0

Without jQuery:

function del_cookie(name) {
    document.cookie = name +
    '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
    }

Now all you need to do is to call this del_cookie() function passing it the name of whatever cookie it is that we wish to delete. The function will update the expiry date on the cookie to one long in the past so that the cookie will be considered to be expired and will be ignored by the browser exactly the same as if it didn't exist

to be used something like

<body onload="SetCookie()" onunload="del_cookie()">

taken from here

Community
  • 1
  • 1
dkapa
  • 267
  • 1
  • 5
  • 15