如何通过 Web Share API 分享您网站上的任何内容

2025-06-09

如何通过 Web Share API 分享您网站上的任何内容

在本文中,我们将探讨Web Share API。借助 Web Share API,Web 应用能够像平台特定应用一样使用系统提供的共享功能。Web Share API 使 Web 应用能够像平台特定应用一样,将链接、文本和文件共享给设备上安装的其他应用。

Web 共享具有以下功能和限制:

  • 它只能在通过 HTTPS 访问的网站上使用。
  • 它必须响应用户操作(例如点击)来调用。
  • 它可以共享 URL、文本或文件。

共享链接和文本

要分享链接和文本,请使用方法。该方法是基于 Promise 的方法,且必须share()包含一个属性对象。为了防止浏览器抛出 错误TypeError,该对象必须至少包含以下属性之一:titletexturlfiles

// check for support of web share API
if (navigator.share) {
  navigator
    .share({
      title: "This is header/title",
      text: "This is the description",
      url: "https://put-here-url.com",
    })
    .then(() => console.log("Successful share"))
    .catch((error) => console.log("Error sharing", error));
} else {
  console.error("Browser doesn't support Web Share API");
}
Enter fullscreen mode Exit fullscreen mode

你可以在你的函数中或任何你想要的地方使用它。但在使用之前,你需要记住一件事:旧版本的浏览器不支持它。

所以你需要确保处理好这种情况。例如,error如果浏览器不支持 Web Share API,上面的代码会显示 console 消息,但我的偏好是,只有浏览器支持时才显示分享按钮,否则隐藏按钮。

以下是我所说的示例代码

const btn = document.getElementById("btn");

// function for web share api
function webShareAPI(header, description, link) {
  navigator
    .share({
      title: header,
      text: description,
      url: link,
    })
    .then(() => console.log("Successful share"))
    .catch((error) => console.log("Error sharing", error));
}

if (navigator.share) {
  // Show button if it supports webShareAPI
  btn.style.display = "block";
  btn.addEventListener("click", () =>
    webShareAPI("header", "description", "www.url.com")
  );
} else {
  // Hide button if it doesn't supports webShareAPI
  btn.style.display = "none";
  console.error("Your Browser doesn't support Web Share API");
}
Enter fullscreen mode Exit fullscreen mode

在 Codepen 上尝试

结论

现在,您可以将此 API 用于个人项目或任何您想要的地方。您可以做更多的事情,例如获取自定义输入,或者分享您的博客,那么您可以使用它。如果您学到了新东西,请点赞👍,并考虑关注。

现在您可以通过给我买一杯咖啡来表示您的支持。😊👇

给我买杯咖啡

另请阅读

鏂囩珷鏉ユ簮锛�https://dev.to/j471n/how-to-share-anything-from-your-website-by-web-share-api-1h5g
PREV
如何在 Tailwind CSS 中使用 ::before 和 ::after
NEXT
彩色雨与 JS AWS Security 同步上线!