[英]Can't set Cookie with JavaScript in Safari or iOS
我正在研究一些 cookie 同意和條款等。所以我制作了一個 JS function 來在用戶點擊“同意”按鈕后設置一個 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);
但沒有任何效果。
有人知道我做錯了什么嗎?
Safari 版本 15.2 與 Chrome 和 Firefox 不同,拒絕在localhost
源上設置Secure
cookies,因此您需要為 Safari 添加解決方法。
您是否嘗試過在 safari 上使用私人標簽? 它可能沒有加載您的新文件。 在我的網站上,我使用相同的方法編寫 cookies,它適用於 Safari。
編碼值是好的
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 件事:
修改后的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
也有助於故障排除
您是否使用其他一些可能會干擾此的框架? 可能有人在背后用 cookies 做事。 您是否也嘗試從 HTTP header 中保存 cookies?
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
您是否嘗試最小化復制器,制作仍然可以復制問題的最小項目? 或者從一個小型的獨立 JS 小提琴開始:
https://jsfiddle.net/ao9p7e4j/1/
這里我加了一個function來顯示cookies看看你有什么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.