我不明白为什么navigator.share()
即使我的网站满足 MDN 上列出的所有要求(具有 HTTPS 并受浏览器支持),也会出现错误。
当我单击按钮时,以下代码出现错误:
shareScoreBtn.addEventListener('click', e => {
if (!(navigator.canShare && navigator.share))
{
console.log('This browser does not support sharing');
showPopup('Error', 'This browser doesn\'t support sharing');
return;
}
const toShare = {
text: 'Check out my score in Perfectly Balanced!',
url: 'https://pb.luisafk.repl.co',
files: [
new File([
deathScreenshots[0]
], 'perfectly-balanced-score.png')
]
};
if (navigator.canShare(toShare))
{
navigator.share(toShare).then(() => {
console.log('Shared death screenshots');
}).catch(err => {
console.error('Error sharing death screenshots:', err);
});
}
else
{
delete toShare.files;
toShare.text = `I got a score of ${score} in Perfectly Balanced!`;
if (navigator.canShare(toShare))
{
navigator.share(toShare).then(() => {
console.log('Shared score text');
}).catch(err => {
console.error('Error sharing score text:', err);
});
}
else
{
showPopup('Error', 'Your browser doesn\'t support sharing');
console.log('This browser does not support sharing the deathScreenshots or text');
}
}
});
我做错了什么?
该网站通过 HTTPS 提供服务,我的浏览器支持 Mozilla 的 Web Share API,我还在控制台中进行了检查!!(navigator.canShare && navigator.share)
不适用于 Windows 10 或 Android 上的 Chrome。
编辑: 它说如果我在控制台工作正常...( promise )
,但该代码中唯一的 promise 是通过navigator.share()
根据MDN无法用 DOMException
拒绝,所以我真的不知道发生了什么。
编辑:很多人误解了这个问题,所以我会澄清它。我的问题是是什么导致navigator.share()
出错?
最佳答案
我认为每次调用 navigator.share()
时,您都需要使用 await
运算符来调用它,如下所示:
await navigator.share();
否则 navigator.share()
返回的 Promise 中引发的任何异常都不会被您的 try
/catch
block 捕获。
关于javascript - navigator.share() 无法在 HTTPS 和支持的浏览器中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73490126/