javascript - 如果支持 Web 共享 API,它应该显示 native 共享对话框,否则它应该转到 anchor 标记的 href 中定义的 URL

标签 javascript jquery web-share

下面的代码在支持 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 ,
  • promise 返回 “中止错误”如果用户选择取消共享操作(主要在移动设备上)或者如果没有可用的共享目标(主要发生在桌面设备上)。因此,区分移动设备和台式计算机上的“AbortError”需要一些额外的机制。
    引用: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/

    相关文章:

    javascript - 向这个 jQuery 脚本添加动画

    带有 jQ​​uery 的 PHP 变量。如果在 <head></head> 中使用 jQuery,则 PHP 变量未定义,但在页脚中使用 jQuery 代码时有效

    javascript - 根据父 div id 加载 Javascript 文件

    javascript - 带有 ajax 奇怪行为的链接下拉菜单

    javascript - navigator.share() 无法在 HTTPS 和支持的浏览器中工作

    javascript - 通过 webshare api 共享文件仅部分适用于 IOS 15

    javascript - 无法从地理位置获取城市名称

    php - 使用 php 和 javascript 从弹出窗口传递多个 MySQL 结果集

    javascript - 通过命令行将html标签插入到html文件中

    javascript - 通过 PWA 的社交媒体分享图片