Javascript 浏览器关闭时删除cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13872305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
delete cookie when browser closed
提问by Doni Andri Cahyono
i need to delete cookie when browser is closed and already put on window.onbeforeunload along with other as following:
我需要在浏览器关闭时删除 cookie,并且已经把 window.onbeforeunload 和其他如下:
window.onbeforeunload = function(){
location.replace("admin.jsp?action=logout");
deleteCookie('Times');
}
with setCookie as following:
使用 setCookie 如下:
function setCookie(name,value,days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else {
expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
when it comes to deleteCookie, it contains as below:
说到deleteCookie,它包含如下:
setCookie(name,value,-1);
The problem is whenever i restart browser, it always comes to window.onbeforeunload so that deleteCookie fired. I actually need this to reset my countdown timer whenever user logs in since the cookie never deleted if the counter doesn't end and user sometimes closes window/tab before it ends. So, my idea is either reset the counter when user logs in or simply delete cookie when user logs out. I still can't figure out how to code this, however. Can anyone help me out? Code snippet will be appreciated, though. CMIIW
问题是每当我重新启动浏览器时,它总是会出现在 window.onbeforeunload 上,以便 deleteCookie 被触发。我实际上需要这个来在用户登录时重置我的倒数计时器,因为如果计数器没有结束并且用户有时在结束之前关闭窗口/选项卡,cookie 永远不会被删除。因此,我的想法是在用户登录时重置计数器或在用户注销时简单地删除 cookie。但是,我仍然无法弄清楚如何对此进行编码。谁能帮我吗?不过,代码片段将不胜感激。CMIIW
回答by Sudhir Bastakoti
Not specifying Expires value on the cookie will cause the cookie to be removed when the browser session ends i.e. when user closes the browser. Like:
不在 cookie 上指定 Expires 值将导致 cookie 在浏览器会话结束时被删除,即当用户关闭浏览器时。喜欢:
Set-Cookie: made_write_conn=1295214458; Path=/; Domain=.foo.com
The made_write_conncookie made_write_conn does not have an expiration date, making it a session cookie. It will be deleted after the user closes his/her browser.
Try doing:
该made_write_conn饼干made_write_conn没有到期日,使其成为一个会话cookie。用户关闭浏览器后,它将被删除。尝试做:
setCookie('Times',value, '');
回答by epascarello
You can not change the page's location when the browser is being closed.
浏览器关闭时无法更改页面位置。
On the server you should be using session end eventsto clean up the account.
在服务器上,您应该使用会话结束事件来清理帐户。

