← 中文资源

简体中文版本

navigator.share 与 canShare 守卫

先探测 navigator.share 是否存在,用 canShare 校验载荷形状可分享,再调用并等待分享面板关闭后兑现的 Promise,不支持时优雅降级。

阅读英文原文

实现说明

navigator.share 与 canShare 守卫的核心是函数 shareReport。 异步部分依次 await 结果,顺序可预测。

使用要点

  • 用到了 navigator,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 演示输出是带标签的(Web Share unsupported here、payload not shareable on this device、report shared),每个操作都会留下自己的一行标注。

常见问题

需要安装第三方包吗?

不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 文件在加载时定义 shareReport。

签名一览:async function shareReport()

核心语句

await navigator.share(payload); // resolves when the share sheet closes
console.log('report shared');
if (!navigator.canShare?.(payload)) {
  console.log('payload not shareable on this device');
  return;
}

代码示例

// navigator.canShare answers whether the payload shape is shareable on this
// device before navigator.share is called with it.
async function shareReport(): Promise<void> {
  const payload = {
    title: 'Weekly deploy report',
    text: '42 deploys, 3 rollbacks',
    url: 'https://devexamples.com/report',
  };

  if (!navigator.share) {
    console.log('Web Share unsupported here');
    return;
  }
  if (!navigator.canShare?.(payload)) {
    console.log('payload not shareable on this device');
    return;
  }
  await navigator.share(payload); // resolves when the share sheet closes
  console.log('report shared');
}