Javascript 此文档如何在未检测到cookie时检测到它';一点也没有?

Javascript 此文档如何在未检测到cookie时检测到它';一点也没有?,javascript,cookies,Javascript,Cookies,这是一个用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"

这是一个用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文件时,是否找到了cookies为什么?当该文档没有保存cookie时,为什么
document.cookie!=“

Cookies是按域和/或路径设置的

示例:

  • http://www.example.com/foo.html
    Cookie:
    x=x;最大年龄=3600岁
    http://www.example.com/*
    ,但不在
    http://other.example.com/
  • http://www.example.com/foo.html
    Cookie:
    x=x;最大年龄=3600岁;domain=.example.com
    http://*.example.com/*
    http://example.com/*
  • 仅限https协议:Cookie:
    x=x;最大年龄=3600岁;安全
  • 可以将路径更改为当前路径或任何父目录。默认路径是当前目录。例如:
    x=x;最大年龄=3600岁;路径=/

@Suhail Gupta-Rob W的意思是,一些html文件可以设置cookie,只要它位于同一个域中,并且cookie(设置时)不限于不同html文件的不同路径,就可以对任何不同的html文件使用。