Web App 透过 Web Share API 就能够使用系统提供的分享功能,将连结、内容和文件分享给安装在装置上的其他应用 App。另外一方面只要透过将 App 配置 Web Share Target 相关设定也能够接收其他 App 分享的内容。
用法上也是很简单,也是只要浏览器有支援 navigator.share
这个 API 就可以使用。使用上需注意
// 一般分享
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 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 站台,使用上:
图片来源: https://web-dev
target.html
页面并显示相关分享内容图片来源: https://web-dev
站台连结: https://web-share.glitch.me/
第 23 天,这几天库存真的用完了,所以文章都是最新鲜,当天写的喔!! 剩下 7 天,一起加油吧! ...
Azure cognitive service: Text-to-Speech- Azure 念给你...
pCloud 是一间注册於瑞士的 IT 资讯公司,目前主要提供专业的线上云端空间服务,所有使用者都...
今日我们将要使用go-elasticsearch来搭配telegram完成讯息发送。 目标 前面章节...
PTT自2017年6月开始实验性开放WebSocket,到2020年1月1日已公告正式支援,现今以W...