如何在所有页面/全局设置Javascript cookie? [英] How to set Javascript cookie in all the pages / globally?
问题描述
我有一个巨大的问题,我的代码,我试图检查是否存在一个cookie,如果它存在,我不想它做任何事情。
I'm having a huge problem with my code, I am trying to check if a cookie exists, and if it does exist, i dont want it to do anything.
它在page1工作罚款,但是当我导航到page2它覆盖了cookie,而不是什么都不做(页面是从同一个网站)
Its working fine on page1, but when i navigate to page2 it overrides the cookie, instead of doing nothing (the pages is from the same website)
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g,"");
if (x == c_name) {
return unescape(y);
}
}
}
var omgpost = getCookie("omgpost");
if (omgpost == null || omgpost == "") {
setCookie("omgpost", "1", 1);
} else {
alert('cookie installed already');
}
这是正常工作,当我没有安装和输入
This is working fine, when I don't have the cookie installed and entering this site, I'm adding the cookie, and I'm getting the confirmation message each time I refresh the page1.
但是,在导航到page2时,它是否重新创建cookie? ??我不想要!
But when navigating to page2 its recreating the cookie??? I don't want that! I want the cookie to be there, and can't be changed, only when it has expired, how can I do that?
推荐答案
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null)
? "" : "; expires="+exdate.toUTCString())
+ "; path=/";
document.cookie=c_name + "=" + c_value;
}
这篇关于如何在所有页面/全局设置Javascript cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!