Web Share API 级别 2 DOMException:权限被拒绝

Oll*_*ams 8 javascript domexception

我正在获取一个 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]
      });
    };
  }
Run Code Online (Sandbox Code Playgroud)

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

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

Den*_*er9 13

您的代码可以稍微优化一下。当前需要指定 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!'
    );
  });  
}
Run Code Online (Sandbox Code Playgroud)

  • @mohamadb 可能是由于文件扩展名。将这些行 `const file = new File([blob], 'rick.jpg', {type: blob.type});` 替换为这两行 `const ext = shareimg.split('.').pop() ; const file = new File([blob], 'image.'+ext, {type: blob.type});` (2认同)