开发者

How this document is able to detect a cookie when it didn't set at all?

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.cook开发者_运维百科ie == "") 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 != "" ?


Cookies are set per domain and/or path.

Examples:

  • http://www.example.com/foo.html Cookie: x=x; max-age=3600; is visible at http://www.example.com/*, but not at http://other.example.com/
  • http://www.example.com/foo.html Cookie: x=x; max-age=3600; domain=.example.com is visible at http://*.example.com/* and http://example.com/*
  • https protocols-only: Cookie: x=x; max-age=3600; secure
  • The path can be changed to the current path, or any parent directory. The default path is the current directory. E.g.: x=x; max-age=3600; path=/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜