Web Share API 不适用于 iOS:Angular

Dha*_*aid 7 javascript typescript angular web-share

我正在尝试通过网络共享像本机应用程序一样的图像。我也在使用Angular。我使用了网络共享 API。这在 Android 上正常工作,但是在 iOS(Safari 和 Chrome)中会引发错误。我正在使用共享按钮来触发它。

这是我的代码:

if (
      this.windowNavigator.canShare &&
      this.windowNavigator.canShare({ files: [file] })
    ) {
      this.windowNavigator
        .share({
          files: [file],
          title: "Vacation Pictures",
          text: "Photos from September 27 to October 14.",
        })
        .then(() => console.log("Share was successful."))
        .catch((error) => console.log("Sharing failed", error));
    } else {
      console.error("Cannot use Web Share API");
    }
Run Code Online (Sandbox Code Playgroud)

我收到的错误是: Cannot use Web Share API

如果浏览器不受支持,通常会发生这种情况。但是,根据https://caniuse.com/#search=web%20share,iOS 上支持 Safari 13。请注意,我尝试将导航器对象记录到控制台,并且它确实具有 share() 原型。我在 HTTPS 服务器上运行它。请指导我如何进行。

Alu*_*dad 5

如您所知,您收到的错误消息是由您自己的代码传播的。当navigator没有canShare属性或navigator.canShare({ files: [file] })返回 falsy时,您会记录错误。

但是您需要使用的 API 是navigator.share 而不是 navigator.canShare,因为对后者的支持更加有限。

根据 MDN 截至 2020 年 5 月 13 日:

在此处输入图片说明

要解决此问题,请考虑以下方法

if (typeof this.windowNavigator.share === "function") {
  try {
    await this.windowNavigator.share({
      files: [file],
      title: "Vacation Pictures",
      text: "Photos from September 27 to October 14.",
    });
    console.log("Share was successful.");
  }
  catch (error) {
    console.log("Sharing failed", error);
  }
}
else {
  console.error("Cannot use Web Share API: API unavailable.");
}
Run Code Online (Sandbox Code Playgroud)

  • 也许我们需要“navigator.canCanShare”,但我认为对此的支持将更加有限 (3认同)