javascript - 无法在 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);
但没有任何效果。
有人知道我在做什么错吗?
解决方案
编码值是好的
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 以查看您拥有的内容
推荐阅读
- json - 如何在应用程序/json文件中换行?
- javascript - SVG.js:为什么旋转的行为很奇怪
- javascript - 量角器:同一页面上的两个下拉菜单(angularJS),只能从一个下拉菜单中成功选择元素
- sql-server - 在 SQL Server 上创建自定义表后,如何将它们添加到 Syspro?
- c++ - 在野兽 1.70.0 中使用 Tcp 超时
- git - 向 COMMIT_EDITMSG 添加文件扩展名
- python - Python函数消息格式化程序
- javascript - 在 CasperJS 中捕获链接跟踪
- json - 有什么方法可以在 json 中使用 Anchor 标签。我正在尝试以文本格式获取相同的标签。我在反应中渲染
- power-automate - 触发传入电子邮件的 API 调用