以下cookie製作代碼適用於Firefox和Explorer,但不適用於Chrome。在FireFox和Explorer中使用Cookie代碼但不使用Chrome
我已設置警報以停止腳本並驗證是否按預期創建了新的Date()對象。所有3個瀏覽器都表示正在創建新的Date(),並且按期望添加10分鐘到期。
流程:登錄頁面 - >
頁這是登錄頁面的創建一個cookie代碼:
/*
Event handler for verify button click.
@param event is the event that triggered this function.
*/
function checkUser(event){
// interesting note: even though the button isn't of type submit, it submits the form.
// this prevents the form from being submitted:
event.preventDefault();
// obtain user name from form
var name = this.form.userName.value;
// obtain password from form
var password = this.form.password.value;
// is the password valid?
if(isValidPassword(password)){
// create new Date object for cookie's expiration
var expires = new Date();
if(expires){
alert(expires.toString());
}
// increase expire time by 10 minutes
expires.setMinutes(expires.getMinutes() + 10);
alert(expires); // Firefox & Chrome show with additional 10 minutes.
// write userName cookie
document.cookie = "userName=" + encodeURIComponent(name) +
"; expires=" + expires.toUTCString();
// write password cookie
document.cookie = "password=" +encodeURIComponent(password) +
"; expires=" + expires.toUTCString();
// password is valid, allow entry to private web page.
location.href = "project3.html";
}else{
// password was not valid
alert("Password must be at least 1 character in length.");
this.form.password.focus();
}
}
然後在放在location.href「project3.html」這樣的代碼,檢查cookie。警報(allCookies)彈出並在Firefox和Explorer中顯示Cookie,但在Chrome中完全空白; ,所以我立即被重定向回登錄頁面。這似乎表明,我的Cookie編寫代碼無法正常工作或Cookie在Chrome中被關閉?但是我選中了「Chrome內容設置」下的Chrome和單選按鈕「允許設置本地數據」。因此,這讓我想到我做了一些Chrome瀏覽器不喜歡的cookie製作的錯誤,您能否發現它並讓我知道問題是什麼?非常感謝。
//
// Ensure user has a right to visit this web page.
//
//attach load event listener to window
window.addEventListener('load', verifyPassword, false);
// attach blur event listener to window
window.addEventListener('blur', verifyPassword, false);
/*
Event handler for window load event. Ensures user has proper credentials
via looking for password name:value pair held in document.cookie collection.
*/
function verifyPassword(){
// decode cookies
var allCookies = decodeURIComponent(document.cookie);
alert(allCookies); // Blank in Chrome; shows cookies in Firefox and Explorer.
var password;
// is the password cookie present?
if(hasCookie("password", allCookies)){
// password cookie present, get password value
password = getCookie("password", allCookies);
}else{
// send user to login page
location.href = "project3_login.html";
}
// password is present, is it valid?
if(isValidPassword(password)){
// they get to stay
// cookie expires in...
}else{
// send user to login page
location.href = "project3_login.html";
}
}
最近發生在我的客戶的同樣的問題。相當奇怪的是,Chrome開發人員工具顯示cookie已設置,但document.cookie未顯示它。 – NBR 2014-11-05 13:48:26