下面的代码在支持 Web 共享 API 的设备上运行良好,并显示 native 共享对话框,但通过“ Uncaught (in promise) DOMException: Share cancelled ”错误,其中 Web 共享 API 不受支持且不会转到在 anchor 标记的 href 中定义的 URL。
<a href="https://example.com?utm_source=btn_share" class="btn-share" target="_blank">
Share on Facebook
</a>
<script type="text/javascript">
$(".btn-share").click(function(e){
// Web Share API
if (navigator.share){
e.preventDefault();
navigator.share({
title: 'This is example website',
url: 'https://example.com'
});
}
});
</script>
如果设备不支持 Web 共享 API,则删除错误,以便它应该转到 anchor 标记的 href 中定义的 URL。
最佳答案
navigator.share()
是一个 promise ,引用:https://www.w3.org/TR/web-share/
目前解决您的问题的最佳方法是:
https://jsfiddle.net/g19but5o/2/
<a href="https://example.com" class="btn-share" target="_blank">
Share on Facebook
</a>
$(".btn-share").click(function(clickEvent){
var self = $(this);
// Web Share API
if (navigator.share){
clickEvent.preventDefault();
navigator.share({
title: 'This is example website',
url: 'https://example.com'
})
.then(function() {
console.log('Successful share');
})
.catch(function(error) {
console.log('Error sharing:', error);
window.open($(self).attr('href'), '_blank');
});
}
});
关于javascript - 如果支持 Web 共享 API,它应该显示 native 共享对话框,否则它应该转到 anchor 标记的 href 中定义的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68125638/