Progressive Web App 透过系统分享内容: Web Share API & Web Share Target (17)

什麽是 Web Share API

Web App 透过 Web Share API 就能够使用系统提供的分享功能,将连结、内容和文件分享给安装在装置上的其他应用 App。另外一方面只要透过将 App 配置 Web Share Target 相关设定也能够接收其他 App 分享的内容。

怎麽使用 Web Share API

用法上也是很简单,也是只要浏览器有支援 navigator.share 这个 API 就可以使用。使用上需注意

  • 只能在 HTTPS 环境
  • 只能透过用户动作触发
  • 支援 URLs、text、files.
// 一般分享
if (navigator.share) {
  navigator.share({
    title: '标题',
    text: '内文',
    url: 'https://hello.share/',
  })
    .then(() => console.log('成功'))
    .catch((error) => console.log('失败', error));
}

// 分享档案
if (navigator.canShare && navigator.canShare({ files: filesArray })) {
  navigator.share({
    files: filesArray,
    title: '标题',
    text: '内文',
  })
  .then(() => console.log('成功'))
  .catch((error) => console.log('失败', error));
} else {
  console.log(`不支援档案分享`);
}

配置 Web Share Target

前面说明了怎麽把内容透过 Web Share API 分享到其他的 App,现在则是透过 Web Share Target 相关配置来让 Progressive Web App 能接收其他 App 分享的内容。

实作上也不困难,我们需要多实作一个页面用来接收分享的内容,并且在 manifest 中加入相关配置,以下的例子就是 target.html,method 预设会是 GET 内容预设编码是 application/x-www-form-urlencoded

{
  "short_name": "Share",
  "name": "Share Target Test",
  "share_target": {
    "action": "target.html",
    "method": "GET",
    "params": {
      "title": "title",
      "text": "text",
      "url": "url"
    }
  },
  // 其他省略
}

在接收到分享後,浏览器会透过 URL-encoded 将相关参数编码并带入 action URL 中 ?title=hello&text=world,接着我们在 target.html 就可以透过相关程序进行处理。

<div>
    <b><code>window.location</code>:</b> <code id="href"></code><br>
    <b>Title:</b> <code id="title"></code><br>
    <b>Text:</b> <code id="text"></code><br>
    <b>URL:</b> <code id="url"></code>
</div>


<script>
    window.addEventListener('DOMContentLoaded', () => {
    document.getElementById('href').textContent = window.location.href;
    const parsedUrl = new URL(window.location);
    document.getElementById('title').textContent = parsedUrl.searchParams.get('title');
    document.getElementById('text').textContent = parsedUrl.searchParams.get('text');
    document.getElementById('url').textContent = parsedUrl.searchParams.get('url');
    });
</script>

Google 的教学文件中,提供了下面这个 Demo 站台,使用上:

  1. 安装
  2. 按分享并选择刚刚安装的 App

图片来源: https://web-dev

  1. 会开启 App 中的 target.html 页面并显示相关分享内容

图片来源: https://web-dev

站台连结: https://web-share.glitch.me/


<<:  铁人赛 Day30 -- 铁人赛最後一天啦

>>:  企划实现(15)

Day 23 - [Android APP] 01-架构介绍-MVVM

第 23 天,这几天库存真的用完了,所以文章都是最新鲜,当天写的喔!! 剩下 7 天,一起加油吧! ...

Day 14 Azure cognitive service: Text-to-Speech- Azure 念给你听

Azure cognitive service: Text-to-Speech- Azure 念给你...

pCloud - 免费 10 GB 云端空间,输入限时优惠码即可取得 3 个月免费 500 GB 储存空间

pCloud 是一间注册於瑞士的 IT 资讯公司,目前主要提供专业的线上云端空间服务,所有使用者都...

Day28 go-elasticsearch(二)

今日我们将要使用go-elasticsearch来搭配telegram完成讯息发送。 目标 前面章节...

Day03 - 连接Ptt WebSocket

PTT自2017年6月开始实验性开放WebSocket,到2020年1月1日已公告正式支援,现今以W...