【问题标题】:Safari ITP 2.0 Storage Access API - Trouble Nesting requestStorageAccess in hasStorageAccess - Non Nested WorksSafari ITP 2.0 存储访问 API - 在 hasStorageAccess 中嵌套 requestStorageAccess 时遇到问题 - 非嵌套作品
【发布时间】:2019-05-19 10:51:10
【问题描述】:

我目前正在尝试实现调用存储访问 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() 所以我不需要嵌套它?

编辑:

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

  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();
    }
  }

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

【问题讨论】:

    标签: javascript cookies iframe safari storage-access-api


    【解决方案1】:

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

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

    【讨论】:

    • 这还能用吗?如果我调用 hasStorageRequest() 如果我之前授予它,我会得到一个真实的值。但是,我仍然无法访问 cookie。只有在用户操作中运行 requestStorageAccess() 之后。能否发一些代码示例或展示一个在线示例?
    • 我还希望您拥有任何代码示例,因为我在按下按钮时调用了 requestStorageAccess,但它仍然不允许存储 cookie。
    • 对不起,这是我 2 年前在一家公司工作的情况,无法访问任何代码来生成示例。只需确保您对 requestStorageAccess 的调用是在单击按钮时直接调用的,而不是在 hasStorageAccess 承诺的解析内。
    猜你喜欢
    • 2019-02-09
    • 2019-03-02
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 2020-07-30
    • 2016-01-16
    • 1970-01-01
    • 2015-10-07
    相关资源
    最近更新 更多