无法在 Safari 上使用存储访问 API 在 iframe 中设置 cookie

Cannot set cookie in iframe using the Storage Access API on Safari

我的页面上有一个 iframe。由于 Safari 会阻止第 3 方 cookie,我正在尝试按照 'Developer Guidance' 下的建议使用存储访问 API:https://webkit.org/blog/10218/full-third-party-cookie-blocking-and-more/. I have copied the following code from 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: 

可以看到,grant好像是成功了,但是还是不能设置cookie。有谁知道出了什么问题吗?

Safari 版本 13.0.1

编辑: Safari 13.1 上的控制台输出:

[Log] hasAccess: false
[Log] error

注意: 封闭页面是一个简单的 iframe 标记,带有指向此页面的 src

TL;DR

确保已在第一方上下文中为域设置 cookie。


该代码示例有几点需要注意。请注意以下是在 Safari 13.1 上测试的。

用户提示的条件和后续的访问授权:

  1. document.requestStorageAccess 必须作为用户操作的结果被调用。尽管如 MDN docs 中所述,document.hasStorageAccess 似乎并未传播用户操作。
  2. 用户必须已经在第一方上下文中与第三方进行过交互。单击文档即可。

能够写入cookie的条件:

必须已经在第一方上下文中的域上设置了 cookie。这个cookie既可以由服务器设置为响应头,也可以由JS使用document.cookie设置。通过一些进一步的测试,似乎不能使用域标志设置此 cookie,以便在第三方上下文中设置后续 cookie。这意味着实际上,现有的 cookie 也必须设置在完全相同的子域上。