6

I have created a cookie by using jQuery. I want to delete the cookie with jQuery when the browser closes. How do I do this?

I've written the following script:

$(function () {
         if ($.cookie('toggle') == "toggle") {
             $('#toggleText').show();
             $('#displayText').text("Less");
         }
         else {
             $('#toggleText').hide();
             $('#displayText').text("More");
         }
         $('#displayText').click(function () {
             if ($(this).text() == "More") {
                 $('#toggleText').show();
                 $(this).text("Less");
                 $.cookie('toggle', 'toggle');

             } else {
                 $('#toggleText').hide();
                 $(this).text("More");
                 $.cookie('toggle', 'nottoggle');

             }
         });

     })

The cookie should also not be deleted when the user refreshes the browser.

Thanks.

bouteillebleu
  • 2,456
  • 23
  • 32
Priyanka
  • 2,802
  • 14
  • 55
  • 88
  • 2
    I think this will help. Identifies the close event and the associated issues http://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser – Crab Bucket Nov 30 '11 at 09:04
  • 1
    JavaScript does not have native support for this. You can detect unload event. Even unload event does not have cross browser support(Latest Web-kit browsers does not support). Please let me know if I am wrong.. – Exception Nov 30 '11 at 09:11
  • 1
    @Sol you are half right ... there is no single cross browser method for the unload event - but if you set a cookie with no expiry date or a date in the past it will be removed when the browser closes – Manse Nov 30 '11 at 09:13

4 Answers4

7

What you are talking about is a transient cookie - cookies are transient (they are removed when the browser is closed) when you set a cookie with no expiry date. They exist for the current browser session only

If you are using this implementation -> http://code.google.com/p/cookies/wiki/Documentation

They provide a delete method :

$.cookies.del('myCookie');
//deletes a cookie, 'myCookie', with default options

Or removing a cookie using pure JavaScript :

document.cookie = "myCookie=; expires=Thu, 01-Jan-70 00:00:01 GMT;";

There is an unload event that you can bind to that will allow you to remove the cookies when the browser closes -

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.

Example :

$(window).unload(function() {
 // delete your cookie here
});

Update ....

It seems that using session cookies with the jQuery plugin isnt as simple as it should be ... i think that using a plugin for such a simple task is a waste of bandwidth (I know its only a couple of KB - but thing of the poor mobile users) .. these are the 2 methods I always use for getting / setting cookies :

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}


function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

And using these methods is very simple ....

setCookie('myCookie','myvalues',5); 
// the 5 is the number of days in the future the cookies should be removed
// leave this parameter out or set to null for transient cookie

myvalues = getCookie('myCookie');

Another Update ....

Its not that difficult with the jQuery plugin, you just need to set some options :

var newOptions = {
  expiresAt: null
};
$.cookies.setOptions(newOptions);
or 
$.cookies.setOptions({expiresAt: null});
Manse
  • 37,765
  • 10
  • 83
  • 108
  • 2
    unload event is calling whenever i'm refreshing browser as well as whenever i'm clicking on any link or any submit button. The event should be only called at the time of browser closing. – Priyanka Nov 30 '11 at 09:20
  • @Priyanka yes - as i said in my answer ... the best way would be to set the cookie with no date - when you initially create it ... i will add the JavaSCript methods for creating cookies - its very simple and really doesnt need a jQuery plugin ... – Manse Nov 30 '11 at 09:21
5

If you want delete cookie when you close browser than you should set a session cookie, which automatically expires when browser closed. But if you want delete cookie when you close a tab than you should use window.unload and window.beforeunload events, write a function to delete necessary cookies and attach to these events.

Emre Erkan
  • 8,433
  • 3
  • 48
  • 53
  • Session cookies SHOULD be removed on browser close except when using Chrome: http://stackoverflow.com/questions/10617954/chrome-doesnt-delete-session-cookies – nickwshaw May 01 '14 at 14:02
1
function deleteCookie(name) {
                setCookie(name,"",-1);
            }
            function setCookie(name,value,days) {
                if (days) {
                    var date = new Date();
                    date.setTime(date.getTime()+(days*24*60*60*1000));
                    var expires = "; expires="+date.toGMTString();
                }
                else expires = "";
                document.cookie = name+"="+value+expires+"; path=/";
            }
$(window).unload(function() {
 deleteCookie('Your cookie to delete name');
});
coolguy
  • 7,866
  • 9
  • 45
  • 71
0

use simple javascript code as mentioned above to create or delete cookie. And if you want to make it as a session cookie(which will expire on browser close) dont pass day parameter.

like

setCookie('test','aa');

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}
Sudhanshu Yadav
  • 2,323
  • 18
  • 18