关闭浏览器时会删除cookie

关闭浏览器时会删除cookie

问题描述:

我有这个cookie来存储用户以前从菜单中选择的内容。但我希望即使用户关闭浏览器,也要将此cookie保存在浏览器中。此代码完全适用于IE,但当我关闭Chrome和Firefox时,cookie被删除。任何人都可以为我提供解决方案。

I have this cookie to store users previous selection from a menu. But I want keep this cookie stored in the browser even if the user closes the browser. This code perfectly works on IE but when I close Chrome and Firefox, the cookie getting deleted. Can anyone provide me solution for this.

function setCookie(NameOfCookie, value, expiredays) {
    var ExpireDate = new Date();
    document.cookie = NameOfCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}

function delCookie (NameOfCookie) {
  if (getCookie(NameOfCookie)) {
    document.cookie = NameOfCookie + "=" + "; expires=Thu, 17-Jul-24 00:00:01 GMT";
  }
}


如果你打电话给这个函数

If you call the function with

setCookie('redirectcountry', 'CA')

然后将失效日期设置为 new Date(),即现在。因此,立即删除cookie是正常行为。

then you set the expiry date to new Date(), that is "right now". So it's normal behavior to have the cookie be immediately deleted.

简单解决方案:将其称为

Simple solution : call it as

setCookie('redirectcountry', 'CA', true)