为什么我不能在Google Chrome中退回Cookie?

时间:2016-05-14 15:28:26

标签: javascript html cookies

我正在使用document.cookie属性练习,我能够在我的FireFox浏览器中设置和返回cookie。但是,当我试图在谷歌浏览器中返回一些cookie时,我没有返回任何内容。这有什么理由吗?这是jsfiddle中的代码。

HTML

<div id="ex1">
    <h2>Example 1</h2>
    <p></p>
    <h4>results:</h4>
    <button id="btn">Return Cookie</button>
    <button id="btn2">Set Cookie</button>
</div>

的Javascript

function cText(text) {
    return document.createTextNode(text);
}

function cElem(elem) {
    return document.createElement(elem);
}

function attach(id, text, elem) {
    var a = cText(text);
    var b = cElem(elem);
    b.appendChild(a);

    var c = document.getElementById(id).appendChild(b);
    return c;
}

document.getElementById('btn').onclick = function() {
    var a = document.cookie;
    attach('ex1', a, 'p');
}

/* In order to make key = values you have to make a  separate line for 
each name and value that you are going to put into the document.cookie*/
document.getElementById('btn2').onclick = function() {
    document.cookie = "name = Michael Hendricks; expires =" + dayt + ";";
    document.cookie = "occupation = Shitty Retail Clerk; expires =" + dayt + ";";
    document.cookie = "age = 26 years old with big ol man boobs; expires =" + dayt + ";";

    console.log('cookie has been saved');
}

2 个答案:

答案 0 :(得分:0)

如果您在localhost上设置cookie,则域必须为null。

答案 1 :(得分:0)

Chrome不会为&#39; file://&#39;设置Cookie。协议(以及safari)。 您可以使用&#39; Web Server for Chrome&#39;测试您的本地网络应用程序。