当 cookie 根本没有设置时,该文档如何能够检测到 cookie?
这是一个使用 some html 文件设置 cookie 的脚本。
window.onload=init;
function init() {
var userName="";
if(document.cookie != "") {
username=document.cookie.split("=")[1];
document.getElementById("name_field").value = username;
}
document.getElementById("name_field").onblur = setCookie;
}
function setCookie() {
var exprDate = new Date();
exprDate.setMonth(exprDate.getMonth() + 6);
var username = document.getElementById("name_field").value;
document.cookie = "username=" + username + ";path=/;expires=" + exprDate.toGMTString();
}
这是另一个带有一些不同 html 文件的脚本(过去没有保存过 cookie),用于检查是否有与此文档一起保存的 cookie。
window.onload = initTest;
function initTest() {
if(document.cookie == "") alert("No,cookies stored !");
else alert("cookies found !");
}
令我惊讶的是,当我使用第二个脚本运行第二个 html 文件时,结果是 找到 cookie 这是为什么?当该文档未保存 cookie 时,怎么会 document.cookie != ""
?
This is one script that sets the cookie with some html file.
window.onload=init;
function init() {
var userName="";
if(document.cookie != "") {
username=document.cookie.split("=")[1];
document.getElementById("name_field").value = username;
}
document.getElementById("name_field").onblur = setCookie;
}
function setCookie() {
var exprDate = new Date();
exprDate.setMonth(exprDate.getMonth() + 6);
var username = document.getElementById("name_field").value;
document.cookie = "username=" + username + ";path=/;expires=" + exprDate.toGMTString();
}
This is another script with some different html file, (that had not saved a cookie in the past) that checks if there is a cookie saved with this document.
window.onload = initTest;
function initTest() {
if(document.cookie == "") alert("No,cookies stored !");
else alert("cookies found !");
}
To my surprise the result when i run the 2nd html file with the second script,is cookies found Why is that ? When that document has not saved a cookie then how come document.cookie != ""
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Cookie 是按域和/或路径设置的。
示例:
http://www.example.com/foo.html
Cookie:x=x; max-age=3600;
在http://www.example.com/*
上可见,但在http://other.example.com/
上不可见代码>http://www.example.com/foo.html
Cookie:x=x;最大年龄=3600; 中可见
http://*.example.com/*
和http://example.com/*
https 协议 -仅:Cookie:x=x;最大年龄=3600; secure
x=x;最大年龄=3600;路径=/
Cookies are set per domain and/or path.
Examples:
http://www.example.com/foo.html
Cookie:x=x; max-age=3600;
is visible athttp://www.example.com/*
, but not athttp://other.example.com/
http://www.example.com/foo.html
Cookie:x=x; max-age=3600; domain=.example.com
is visible athttp://*.example.com/*
andhttp://example.com/*
x=x; max-age=3600; secure
x=x; max-age=3600; path=/