2011-05-23 56 views
16

這裏就是我希望做的(僞代碼):檢查,否則設置的Cookie在10天內到期

想象中的例子cookie的名稱是「參觀」,它包含沒有。

if visited exists 
then alert("hello again"); 
else 
create visited - should expire in 10 days; 
alert("This is your first time!") 

如何在JavaScript中實現此目的?

回答

58

你需要讀寫document.cookie

if (document.cookie.indexOf("visited=") >= 0) { 
    // They've been here before. 
    alert("hello again"); 
} 
else { 
    // set a new cookie 
    expiry = new Date(); 
    expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes 

    // Date()'s toGMTSting() method will format the date correctly for a cookie 
    document.cookie = "visited=yes; expires=" + expiry.toGMTString(); 
    alert("this is your first time"); 
} 
+1

是expires'過時的,順便說一句。 – Ryan 2011-05-23 02:54:40

+1

如果'expires'已過時,您將如何過期cookie – aamiri 2012-01-24 15:44:05

+7

@aamiri較新的替代方案是'max-age = numseconds',用於在設置cookie'numseconds'後過期。在這裏查看其他答案的用法。 – 2012-01-24 15:57:09

20
if (/(^|;)\s*visited=/.test(document.cookie)) { 
    alert("Hello again!"); 
} else { 
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days. 
    alert("This is your first time!"); 
} 

是一種方法。請注意0​​是一個神奇的屬性,所以你不必擔心覆蓋任何東西。

也有more convenient libraries to work with cookies,如果您不需要將您存儲的信息發送到服務器上的每個請求,HTML5’s localStorage and friends是方便和有用的。

+3

瀏覽器修復:'/(?^ |; \ S)到訪= /'' – 2014-01-20 00:55:31