Navigator.share 在 iOS 中仅工作一次,第二次单击会抛出错误“用户代理不允许请求...”

Rya*_*yan 5 javascript safari ios web-share

还有其他人遇到过这个问题吗?我正在实现 Web Share API,以将共享按钮添加到页面上的多个列表中。该代码最初似乎工作正常,因为我可以单击任何“共享”按钮,对话框将正确显示。

但是,如果我关闭该对话框并尝试再次单击它,则会收到一条错误消息,提示“当前上下文中的用户代理或平台不允许该请求,可能是因为用户拒绝了权限。”

更奇怪的是,我在所有这些关于如何实现 Web Share API 的教程网站上都遇到了同样的行为(例如: https: //alligator.io/js/web-share-api/ - 尝试单击“分享我!”)在 iOS Safari 上,多次在页面中间放置“按钮。)

这是我的代码供参考:

const shareButtons = document.querySelectorAll('.share');

for (const button of shareButtons) {
    button.addEventListener("click", async () => {
        if (navigator.share) {
            try {
                await navigator.share({ 
                    url: button.getAttribute('data-url')
                });
            } catch (err) {
                  alert(err.message);
            }
        } else {
            // fallback
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

感谢我对此的任何见解 - 非常感谢

dav*_*rve 2

您使用的是哪个版本的 IOS?

IOS 14.0.1 中似乎存在一个已知错误,最初的承诺无法解决。

https://developer.apple.com/forums/thread/662629

文章中建议的修复(对我有用)是:

navigator.share(...)
.then(() => {
    // this will never happen in IOS 14.0.1
})
.catch(error => {
    //this will catch the second share attempt
    window.location.reload(true); // now share works again
});
Run Code Online (Sandbox Code Playgroud)

或者在你的情况下使用 try/catch

const shareButtons = document.querySelectorAll('.share');

for (const button of shareButtons) {
    button.addEventListener("click", async () => {
        if (navigator.share) {
            try {
                await navigator.share({ 
                    url: button.getAttribute('data-url')
                });
            } catch (err) {
                  // this will catch the second share attempt on ios14
                  window.location.reload(true); // now share works again
                  alert(err.message);
            }
        } else {
            // fallback
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

缺点是,它实际上意味着如果用户使用 IOS14,则必须单击两次才能触发第二次共享 - 但其他用户不会发生这种情况