我的页面上有一个 iframe。由于 Safari 阻止了第 3 方 cookie,我正在尝试使用“开发人员指南”下建议的存储访问 API:https://webkit.org/blog/10218/full-third-party-cookie-blocking-and-more/ .我从 the documentation 复制了以下代码:
<script type="text/javascript">
window.addEventListener('load', () => {
document.getElementById('test-button').addEventListener('click', () => {
document.hasStorageAccess().then(hasAccess => {
console.log('hasAccess: ' + hasAccess);
if (!hasAccess) {
return document.requestStorageAccess();
}
}).then(_ => {
console.log('Now we have first-party storage access!');
document.cookie = "foo=bar";
console.log(`document.cookie: ${document.cookie}`);
}).catch(_ => {
console.log('error');
});
});
});
</script>
<button id="test-button">Test</button>
浏览器控制台输出:
[Log] hasAccess: true
[Log] Now we have first-party storage access!
[Log] document.cookie:
如您所见,授权似乎成功但仍然无法设置 cookie。有谁知道出了什么问题?
Safari 版本 13.0.1
编辑: Safari 13.1 上的控制台输出:
[Log] hasAccess: false
[Log] error
注:附页是一个简单的
iframe
带有 src
的标签指向这个页面。
最佳答案
TL;博士
确保已在第一方上下文中为域设置了 cookie。
该代码示例有几件事需要注意。请注意,以下内容是在 Safari 13.1 上测试的。
用户提示的条件和随后的访问权限:
document.requestStorageAccess
必须作为用户操作的结果来调用。尽管如 MDN docs 中所述, document.hasStorageAccess
似乎没有传播用户操作。 能写cookie的条件:
必须已经在第一方上下文中的域上设置了 cookie。该 cookie 可以由服务器设置为响应头,也可以由 JS 使用 document.cookie 设置。通过一些进一步的测试,似乎这个 cookie 不能使用域标志设置,以便在第三方上下文中设置后续 cookie。这意味着实际上,现有的 cookie 也必须设置在同一个确切的子域上。
关于javascript - 无法使用 Safari 上的存储访问 API 在 iframe 中设置 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61019608/