首页 > 解决方案 > 无法在 Safari 或 iOS 中使用 JavaScript 设置 Cookie

问题描述

我正在研究一些 cookie 同意和条款等。所以我做了一个 JS 函数来在用户单击“同意”按钮后设置一个 cookie:

...html

<button onclick="setCookie('law_cookie', 'agree_all', 90)">


...js

function setCookie(name, value, daysToLive) {
    // Encode value in order to escape semicolons, commas, and whitespace
    let cookie = name + "=" + encodeURIComponent(value);

    if (typeof daysToLive === "number") {
        /* Sets the max-age attribute so that the cookie expires
        after the specified number of days */
        cookie += ";max-age=" + (daysToLive * 24 * 60 * 60) + ';Secure;path=/';

        document.cookie = cookie;
        cookie_set = true

    }
}

现在我在 chrom 和 firefox 中进行了测试,一切都很好!但是,safari 无法设置 cookie。我尝试通过单击按钮进行初始化,但重新加载 safari 后没有设置 cookie。

我检查了是否启用了javascript(它是),我也尝试设置cookie = encodeURIComponent(cookie);但没有任何效果。

有人知道我在做什么错吗?

标签: javascriptcookiessafarisetcookie

解决方案


编码值是好的

let cookie = name + "=" + encodeURIComponent(value);

但编码整个刺痛不是:

cookie = encodeURIComponent(cookie);

我修改了你的脚本我删除了“安全”条目,因为这将限制它只能使用 HTTPS,当你进行故障排除时,给它最好的机会,并且只有在一切正常时才添加安全性。在过去,可能适用于某些浏览器:

https://developer.mozilla.org/en-US/docs/web/api/document/cookie

;secure Cookie to only be transmitted over secure protocol as https. Before Chrome 52, this flag could appear with cookies from http domains.

我补充说window.alert,你会看到 3 件事:

  • 证明您的按钮/事件实际命中
  • 检查您是否提供了年龄参数(没有年龄,您的条件将不会保存 cookie)
  • 将向您显示要保存的值,以便您确认是否可以。

修改后的JS:

function setCookie(name, value, daysToLive) {
    // Encode value in order to escape semicolons, commas, and whitespace
    let cookie = name + "=" + encodeURIComponent(value);

    if (typeof daysToLive === "number") {
        /* Sets the max-age attribute so that the cookie expires
        after the specified number of days */
        cookie += ";max-age=" + (daysToLive * 24 * 60 * 60) + ';path=/';

                window.alert(cookie);
        document.cookie = cookie;
        cookie_set = true
    }
}

setCookie('law_cookie', 'agree_all', 90)

经常使用很多console.log帮助进行故障排除

您是否使用其他一些可能会干扰这一点的框架?有些东西可能在你背后用饼干做事。您是否也尝试从 HTTP 标头中保存 cookie?

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie

您是否尝试最小化复制器,制作仍然可以复制问题的最小项目?或者从一个小的独立 JS fiddle 开始:

https://jsfiddle.net/ao9p7e4j/1/

在这里,我添加了一个功能来显示 cookie 以查看您拥有的内容


推荐阅读