我目前正在尝试实现调用存储访问 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();
}
}
仍然进入“失败”功能......