Dhaval Rajani
Dhaval Rajani

Reputation: 311

Delete cookie on browser close not on page refresh

I seen many post regarding same problem but i am not getting exact solution. i want to delete cookie on browser or tab close event using javascript. I have made delete cookie function and called on onbeforeunload event. But i seen that event also called when page refresh i dont want to delete cookie on page refresh. And i seen in many post that they are detecting link click, keypress event of F5 and form submit and in that they preventing onbeforeunload event. But then what about refresh button click and press enter at url bar. So i think this is not a exact solution. so help me out from this problem.

Further information is i am creating cookie using PHP and want to delete this cookie on browser close.

Upvotes: 3

Views: 15816

Answers (3)

karvin.developer
karvin.developer

Reputation: 556

To delete all the cookies when browser close uses the following code

$(window).bind('beforeunload', function(event) {    
    var cookies = $.cookie();
      for(var cookie in cookies) {
        $.removeCookie(cookie);
      }
    return true;
});

Hope this will solve your problem.

Upvotes: 0

Deepak Vishwakarma
Deepak Vishwakarma

Reputation: 106

If you want to delete a cookie on browser close, better would be to check if cookie exists on page load and delete that.

Upvotes: 0

Maroun Baydoun
Maroun Baydoun

Reputation: 464

Cookies are automatically deleted when the browser is closed, unless you specify a lifetime for the cookie.

Upvotes: 13

Related Questions