Safari ITP 2.0 存储访问 API - 在 hasStorageAccess 中嵌套 requestStorageAccess 时出现问题 - 非嵌套工作

2024-04-09

我目前正在尝试实现调用存储访问 API,但在将 requestStorageAccess 的调用嵌套在 hasStorageAccess 中时遇到问题。

这是代码的概要 - 它相当标准:

  requestStorageAccessAndServe() {
    let thisObject = this;
    var promise = document.hasStorageAccess();
      promise.then(
        function (hasCookieAccess) {
          if (!hasCookieAccess) {
            document.requestStorageAccess().then(
                function successful() {
                  // reload iframe to run with cookie access
                  window.location.reload();
                },
                function fail() {
                  thisObject.serveContent();  // Code goes into here
                });
          } else {
            thisObject.serveContent();
          }
        },
        function (reason) {
          thisObject.serveContent();
        }
      );

  }

当点击按钮触发这个方法时,我总是陷入“失败”功能,没有出现请求存储访问的提示。

令人惊讶的是,这段非嵌套代码运行良好:

  requestStorageAccessAndServe() {
    let thisObject = this;
    let hasCookieAccess = !!document.cookie;
    if (!hasCookieAccess) {
      document.requestStorageAccess().then(
          function successful() {
            window.location.reload();
          },
          function fail() {
            thisObject.serveContent();
      });

    } else {
      thisObject.serveContent();
    }
  }

这段代码有效 - 它在第一个请求时重新加载 iframe,然后在重新加载另一个请求后提供数据,但是通过执行 !!document.cookie 检查 cookie 访问非常困难(如果一开始就没有 cookie 数据怎么办? ),我更想了解这里出了什么问题。有人有什么主意吗?

对于可能的解决方案,有什么方法可以强制解析 document.hasStorageAccess() 这样我就不需要嵌套它?

Edit:

强迫承诺解决也无济于事。参见代码示例:

  async requestStorageAccessAndServe() {
    let thisObject = this;
    let hasCookieAccess = await document.hasStorageAccess();
    if (!hasCookieAccess) {
      document.requestStorageAccess().then(
          function successful() {
            window.location.reload();
          },
          function fail() {
            thisObject.serveContent();
      });

    } else {
      thisObject.serveContent();
    }
  }

仍然进入“失败”功能......


这里的问题是 requestStorageAccess() 需要调用用户意图。通过将其嵌套在 hasStorageAccess() Promise 中,用户意图(点击)会被掩盖,并且 Safari 会自动拒绝该请求。

为了解决这个问题,我在 iframe 加载上解析 hasStorageAccess(因为它不需要用户意图),将此结果存储在类变量中,然后如果它解析为 false,我会在单击时检查 requestStorageAccess。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Safari ITP 2.0 存储访问 API - 在 hasStorageAccess 中嵌套 requestStorageAccess 时出现问题 - 非嵌套工作 的相关文章

随机推荐