【问题标题】:Web Share API level 2 DOMException: Permission deniedWeb 共享 API 级别 2 DOMException:权限被拒绝
【发布时间】:2020-03-05 01:35:30
【问题描述】:

我正在获取一个 img,将其转换为一个文件,然后尝试共享该文件。我在 Android 上的最新 Chrome 上测试了代码(目前唯一支持此 API 的浏览器)。

  if (shareimg && navigator.canShare) {
    share = async function() {
      const response = await fetch(shareimg);
      const blob = await response.blob();
      const file = await new File([blob], "image.jpeg");

      navigator.share({
        url: shareurl,
        title: sharetitle,
        text: sharetext,
        files: [file]
      });
    };
  }

我正在运行该函数以响应用户单击按钮(必须从用户手势调用 share() 方法,否则它将不起作用)。

(我正在使用 Browserstack 测试此代码,它为 javascript 错误提供了一个控制台,因为我无法成功地将我的 Android 设备链接到我的 mac 进行调试,并且此 API 仅适用于手机 - 不适用于桌面版 Chrome。 )

【问题讨论】:

    标签: javascript domexception


    【解决方案1】:

    您的代码可以稍微优化一下。当前需要指定 blob 的 MIME 类型。你可以在这里查看下面的代码:https://statuesque-backpack.glitch.me/

    if ('canShare' in navigator) {
      const share = async function(shareimg, shareurl, sharetitle, sharetext) {
        try {
          const response = await fetch(shareimg);
          const blob = await response.blob();
          const file = new File([blob], 'rick.jpg', {type: blob.type});
    
          await navigator.share({
            url: shareurl,
            title: sharetitle,
            text: sharetext,
            files: [file]
          });
        } catch (err) {
          console.log(err.name, err.message);
        }
      };
    
      document.querySelector('button').addEventListener('click', () => {
        share(
          'https://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Rick_Astley_Dallas.jpg/267px-Rick_Astley_Dallas.jpg',
          'https://en.wikipedia.org/wiki/Rick_Astley',
          'Rick Astley',
          'Never gonna give you up!'
        );
      });  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      • 2021-06-23
      • 2023-03-19
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多