【问题标题】:Why can't I return cookies in Google Chrome?为什么我无法在 Google Chrome 中返回 cookie?
【发布时间】:2016-05-15 00:50:59
【问题描述】:

我正在练习使用 document.cookie 属性,并且能够在我的 FireFox 浏览器中设置和返回 cookie。但是,当我尝试在 google chrome 中返回一些 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');
}

【问题讨论】:

  • 您的 jsfiddle 在我的 50.0.2661.102 Chrome 中运行良好
  • @Gosha_Fighten 是的,我看到它在 jfiddle 中有效。但是当我将它添加到常规 html 文件中并在 chrome 中输出时,我不会返回任何值。

标签: javascript html cookies


【解决方案1】:

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

【讨论】:

  • 如何使域为空?
【解决方案2】:

Chrome 不会为“file://”协议(以及 safari)设置 cookie。 您可以使用“Web Server for Chrome”来测试您的本地网络应用。

【讨论】:

    猜你喜欢
    • 2017-04-12
    • 2016-05-14
    • 2021-02-01
    • 2014-08-27
    • 2021-01-20
    • 1970-01-01
    • 2015-09-21
    • 2022-08-24
    • 2020-11-03
    相关资源
    最近更新 更多