本文介绍了不同浏览方案中的Javascript cookie到期/删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

客户端请求cookie功能,如果浏览器未关闭,则cookie有30分钟到期,但如果/当用户关闭浏览器时需要删除它。

A client requested cookie functionality where if the browser is not closed, the cookie has a 30 minute expiration, but then it needs to be removed if/when a user closes the browser.

以下是我要做的事情:

delCookie = function() {
    document.cookie = 'cookieName=;expiration=Thu, 01-Jan-70 00:00:01 GMT;';
};

$(window).unload(function() {
    delCookie();
})

然后我意识到,当用户导航到另一个站点时,它还会触发.unload,这将删除cookie而不是保持cookie过期。

I then realized that when user navigates to a different site, it also triggers .unload which will delete the cookie instead of keeping the cookie with expiration.

当浏览器关闭或用户离开网站时,我有什么方法可以使用javascript检测?

Is there any way I can detect using javascript when browser is being closed or a user is navigating away from the site?

推荐答案

卸载是检测用户已离开您网站的标准方法(关闭窗口/标签或导航离开)

unload is the standard method of detecting that the user has left your site (either closed the window/tab or navigated away)

您需要记住,如果用户导航,您将无法再运行应用程序中的代码。

You need to remember that if a user navigates away you cannot run code from your application anymore.

要回答您的问题 - 您发布的代码是您在方案中获得的最大灵活性。

To answer your question - the code you posted is the most flexibility you will get with your scenario.

这篇关于不同浏览方案中的Javascript cookie到期/删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 10:55