[译] Web Share API 教程

1,553 阅读3分钟

原文链接:The Web Share API, from alligator.io

Web Share API 帮助开发者在 Web App 中使用设备原生的分享功能,而不是借助各个社交平台和 DIY 实现脚本。

API 的接口使用很简单。整个规范 几分钟也就读完了。为了跟规范精神保持一致,这篇文章也力求简洁与亲切。

使用

从下面几条开始学习它的使用:

  • 网站和 Web App 都要是基于 HTTPS 请求之上的。开发的时候,本地的 localhost 也受支持。
  • navigator.share 方法必须是由用户手势(比如点击按钮)发起的调用才有效。像在页面 load 后调用就无效,这是为了避免接口的滥用。

首先,要检查浏览器是否支持 Web Share API。通过检查 navigator.share 是否定义就行了。

if (navigator.share) {
  // we can use web share!
} else {
  // provide a fallback here
}

navigator.share 方法返回的是一个 Promise 对象,接受一个选项对象参数设置分享内容。参数对象至少包含 texturl 两个属性配置,还可以传递一个可选的 title 属性配置。

下面举一个简单的例子。注意,分享逻辑写在了点击事件处理器中,就是为了满足“由用户手势发起的调用”这一条件:

const shareBtn = document.querySelector('.share-btn');

shareBtn.addEventListener('click', () => {
  if (navigator.share) {
    navigator.share({
      title: 'My awesome post!',
      text: 'This post may or may not contain the answer to the universe',
      url: window.location.href
    }).then(() => {
      console.log('Thanks for sharing!');
    })
    .catch(err => {
      console.log(`Couldn't share because of`, err.message);
    });
  } else {
    console.log('web share not supported');
  }
});

你也可能会使用页面标题和 canonical URL 作为分享内容,写法上就稍微复杂那么一点点。

const shareBtn = document.querySelector('.share-btn');
const ogBtnContent = shareBtn.textContent;
const title = document.querySelector('h1').textContent;
const url = document.querySelector('link[rel=canonical]') &&
            document.querySelector('link[rel=canonical]').href ||
            window.location.href;

shareBtn.addEventListener('click', () => {
  if (navigator.share) {
    navigator.share({
      title,
      url
    }).then(() => {
      showMessage(shareBtn, 'Thanks! 😄');
    })
    .catch(err => {
      showMessage(shareBtn, `Couldn't share`);
    });
  } else {
    showMessage(shareBtn, 'Not supported');
  }
});

function showMessage(element, msg) {
  element.textContent = msg;
  setTimeout(() => {
    element.textContent = ogBtnContent;
  }, 2000);
}

在该示例中,共享按钮的文本修改会保持 2 秒钟,显示共享是否成功。导致共享失败的原因,包括浏览器不支持 Web Share API,或者分享中产生错误。

如果你使用的浏览器支持此功能,就会看到类似下面的结果:

大家可以去原网页中点击,查看效果

一些琐碎的知识点

上面代码里获取 url 地址部分的语句可能会让你感觉有点疑惑。

const url = document.querySelector('link[rel=canonical]') &&
            document.querySelector('link[rel=canonical]').href ||
            window.location.href;

下面列出一些测试代码,可能你就懂了。

55 && 777; // 777
55 && 777 || 999; // 777
55 && 0 || 999; // 999

逻辑运算符 &&|| 的行为有点出乎意料,它返回的不是布尔值,而是根据真假值,返回表达式中运算数之一。参照 MDN 上的《逻辑运算符》文档 了解更多。

我们首先检查 <link rel="canonical"> 是否存在,有的话,就使用这个标签的 href 值。否则,回退使用 window.location

你可能还注意到了,我们还使用了 对象字面量的简洁表示法。因为这里的变量名与对象属性名是一样的。

兼容性

image.png

支持情况不太好。苹果 Safair 浏览器已经都支持了,从安卓上的 Chrome 浏览器从 79 开始支持。

上面是全球数据。再看下我们国内的浏览器支持情况(根据使用率)。

image.png

还是可以考虑在移动端最作为渐进特性使用的。

(正文完)


广告时间(长期有效)

我有一位好朋友开了一间猫舍,在此帮她宣传一下。现在猫舍里养的都是布偶猫。如果你也是个爱猫人士并且有需要的话,不妨扫一扫她的【闲鱼】二维码。不买也不要紧,看看也行。

(完)