neo
neo

Reputation: 2471

JQuery and Cookie: How to remove them when user leaves the page or exit window/tab

I am learning to use this JQuery cookie plugin at https://github.com/carhartl/jquery-cookie

From what I have read, it's really easy to read and remove a cookie. My question is: I want the cookie to be removed when the user navigates away from the page or close the window/tab, how do I do that? How do I detect such activity?

Thanks.

Upvotes: 3

Views: 8564

Answers (2)

Lucas Rueda
Lucas Rueda

Reputation: 176

The update to the accepted answer would be:

Cookies.remove('name');

With: https://github.com/js-cookie/js-cookie

The jQuery plugin is not longer mantained.

Upvotes: 0

palaѕн
palaѕн

Reputation: 73906

$(window).on('beforeunload', function () {
    // Remove the cookie
    $.cookie("name_of_cookie", null);
});

Also, we have one more option:

$(window).unload(function () {
    // Remove the cookie
    $.cookie("name_of_cookie", null);
});

Upvotes: 5

Related Questions