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

标签 javascript iframe safari storage-access-api

我的页面上有一个 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/

    相关文章:

    php - Facebook应用未显示youtube嵌入视频

    Safari 和 IE 中的 CSS 问题

    html - Flexbox 和 Position Absolute without Top/Bottom in Chome vs. FF & IE

    javascript - 无法更改数据表中的页面

    javascript - 在 jQuery 中将 JSON 数据传递给 .getJSON?

    javascript - 停止缩放 iframe 中的内容并继续滚动页面

    javascript - 检测来自 iframe 的事件与父级上的 jQuery 事件监听器一起使用,但现在使用纯 JS

    javascript - 使用 onbeforeunload 时抑制确认对话框

    javascript - 加载 js 文件时出现问题

    css - Safari 错误?使用 GSAP 翻译表行组使标题跳到底部