JQuery和Cookie:如何在用户离开页面或退出窗口/选项卡时删除它们

neo*_*neo 3 html javascript cookies jquery

我正在学习如何在https://github.com/carhartl/jquery-cookie 上使用这个JQuery cookie插件

从我所看到的,它非常容易阅读和删除cookie.我的问题是:当用户离开页面或关闭窗口/标签时,我希望删除cookie,我该怎么做?我如何检测此类活动?

谢谢.

pal*_*aѕн 5

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

此外,我们还有一个选择:

$(window).unload(function () {
    // Remove the cookie
    $.cookie("name_of_cookie", null);
});
Run Code Online (Sandbox Code Playgroud)