2010-09-25 61 views

回答

72

代碼:

var now = new Date(); 
var time = now.getTime(); 
time += 3600 * 1000; 
now.setTime(time); 
document.cookie = 
'username=' + value + 
'; expires=' + now.toUTCString() + 
'; path=/'; 
+0

謝謝 - 我正在使用.toGTMString - 沒有意識到它已被棄用! – 2014-05-06 21:13:55

5

你可以在一個更緊湊的方式寫:

var now = new Date(); 
now.setTime(now.getTime() + 1 * 3600 * 1000); 
document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/"; 

對於像我這樣的人,他浪費了一個小時的時間,試圖弄清爲什麼沒有設置過期cookie(但沒有過期可以在Chrome中設置),這裏是回答:

由於某些奇怪的原因,Chrome團隊決定忽略來自本地頁面的Cookie。因此,如果您在本地主機上執行此操作,您將無法在Chrome中看到您的Cookie。因此要麼將其上傳到服務器上,要麼使用其他瀏覽器。

+0

你的方式行爲怪異.... – 2017-02-28 14:36:02

相關問題