navigator.share


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>navigator.share</title>
  </head>
  <body>
    <!-- <a href="./ji.gif" download="ji.gif">ji.gif</a> -->
    <button type="button" class="btn-share">分享</button>

    <script>
      // navigator.share 调用设备的本机共享机制来共享文本、URL 或文件等数据

      const shareBtn = document.querySelector('.btn-share');

      const url = 'https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/canShare';

      const shareData = {
        title: '这是分享的标题',
        // text: '这是分享的文本',

        // url: 'https://fastly.picsum.photos/id/924/200/300.jpg?hmac=9Zu3ewQYhI2ltbuwGQk-Ed6PjR87O-zdiPty45pJS6g',
      };

      shareBtn.addEventListener('click', async () => {
        if (!navigator.canShare) {
          return alert('当前浏览器不支持 navigator.canShare');
        }
        // const imgBlob = await fetch('./ji.gif').then((res) => res.blob());
        // const file = new File([imgBlob], 'share.gif', { type: imgBlob.type });
        // shareData.files = [file];

        const canShare = navigator.canShare(shareData);
        console.log(`支持 navigator.canShare => `, canShare);

        if (canShare) {
          try {
            await navigator.share(shareData);
          } catch (err) {
            alert('分享失败' + err);
            console.log('share err => ', err);
          }
        }
      });
    </script>
  </body>
</html>
posted @ 2024-05-12 20:46  _clai  阅读(11)  评论(0编辑  收藏  举报