Web 共享 API Web 共享 API

2025-06-09

Web 共享 API

Web 共享 API

Web 共享 API

如果您想了解 Web Share API 的实际运行情况,这里有一个 CodePen链接可以尝试一下。

Web Share API 使 Web 应用程序能够共享数据,例如:链接、文本和文件,就像在本机应用程序中一样。

一些要求

在您将这个 API 添加到您自己的 Web 项目之前,有两件主要的事情需要注意:

  • 您的网站必须通过 HTTPS 服务。即使您的网站在本地服务器上运行,该 API 也能正常工作,因此您仍然可以在本地进行测试。
  • 只能在响应用户操作(例如按钮click事件)时调用

使用 Web 共享 API

要开始使用 Web Share API,请将一个对象传递给share()navigator对象上基于 Promise 的方法。对象上的每个属性都是可选的。但是,您传递的对象必须至少包含以下属性之一:titletext或 ,url才能files正常工作而不会引发错误。

navigator
  .share({
    title,
    text,
    url
  })
  .then(() => {
    console.log("");
  })
  .catch(error => {
    console.log(error);
  });

分享带有文本的链接

要共享带有文本的链接,我们调用该navigator.share()方法并传递包含以下至少一个字段的对象:

  • url:代表您想要分享的链接的字符串(您可以在此处获取页面 URL)。
  • title:表示您想要共享的数据标题的字符串(您可以在此处获取页面标题)。
  • text:表示您想要包含的任何文本的字符串。

因此,如果我们想在本地共享此内容:

  • 网址'<Github repo name>'
  • 标题"Web Share API"
  • 文本"Sent with the Web Share API"

实现如下:

navigator
  .share({
    title: "Web Share API",
    text: "Sent with the Web Share API",
    url: "<Github repo name>"
  })
  .then(() => {
    console.log("Shared successfully.");
  })
  .catch(error => {
    console.log("There was an error sharing:", error);
  });

请记住,并非所有浏览器都支持 Web Share API,因此我们将检查用户的浏览器是否支持它:

if (navigator.share) {
  navigator
    .share({
      title: "Web Share API",
      text: "Sent with the Web Share API",
      url: "<Github repo name>"
    })
    .then(() => {
      console.log("Shared successfully.");
    })
    .catch(error => {
      console.log("There was an error sharing:", error);
    });
} else {
  console.log("The Web Share API is not supported in your browser.");
}

由于 API 只能由click事件触发,因此我们将把所有代码包装在按钮触发器周围:

button.addEventListener("click", event => {
  if (navigator.share) {
    navigator
      .share({
        title: "Web Share API",
        text: "Sent with the Web Share API",
        url: "<Github repo name>"
      })
      .then(() => {
        console.log("Shared successfully.");
      })
      .catch(error => {
        console.log("There was an error sharing:", error);
      });
  } else {
    console.log("The Web Share API is not supported in your browser.");
  }
});

瞧!快来试用Web Share API 的演示版吧!

浏览器支持

此 Web 分享 API 目前仅支持 Android 版 Chrome 浏览器以及桌面版和 iOS 版 Safari 浏览器。在撰写本文时,它仍处于实验阶段,因此预计未来某些行为可能会有所变更。

资源

鏂囩珷鏉ユ簮锛�https://dev.to/juwanpetty/web-share-api-373b
PREV
Map 是如何工作的?哈希算法 一切都是整数 哈希碰撞 整合所有元素 奖励环节:集合 透视 结论
NEXT
如何从您自己的域名为*任何*网站提供服务(免费!)