| 2 min read

Chrome 75 开始支持 Web Share API - Level 2, 这也就意味着你可以通过 JS 分享 文件,链接或者文本到其他的 App 了。

其实这个需求很早很早,我们的 PM 就开始提了,关于实现,目前比较成熟的是通过 JS Bridge,然后利用 APP 的能力唤起分享面板。但是我们还是无法通过 Chrome 或者 Safari 实现页面内通过 JS 执行唤起分享面板。详情可以见《H5 互动营销》

canShare() 以及 share()

当然目前这个还是一个处在实验性的 API ,我们还是需要去做一些兼容性判断。分享文件,我们还需要确认这些文件是否处于可分享的状态。可以尝试 Chrome 团队给的代码

const shareData = { files: filesArray };
if (navigator.canShare && navigator.canShare(shareData)) {
  // Share the data.
} else {
  console.log('Your system doesn't support sharing files.');
}

需要注意的是,shareData 里面不能包含其他元素,如果你需要指定文本或者 URL,你可以在后面申明。你可以分享视频,图片以及一些文本文件,关于 mimeType 的限制可以参考 Chrome 的文档

if (navigator.canShare && navigator.canShare( { files: filesArray } )) {
  navigator.share({
    files: files,
    title: 'Vacation Pictures',
    text: 'Barb\nHere are the pictures from our vacation.\n\nJoe',  })
  .then(() => console.log('Share was successful.'))
  .catch((error) => console.log('Sharing failed', error));
} else {
  console.log('Your system doesn't support sharing files.');
}

大家最常用的可能还是分享当前网站到其他渠道。

$('.js-share-web').on('click', function() {
            if (navigator.canShare) {
                navigator.share({
                    text: 'Web Share API',
                    url: '',
                })
                .then(function() {console.log('Share was successful.')})
                .catch(function(error) {console.log('Sharing failed', error)});
            } else {
                alert('Browser Cannot Share')
            }
});

体验地址 https://wicg.github.io/web-share/demos/share-files.html

运行效果为

备注 一定是 Chrome 版本 >= 75; Android 体验地址 https://chrome.en.uptodown.com/android/download

You Can Speak "Hi" to Me in Those Ways