什麼是 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 站台,使用上:
- 安裝
- 按分享並選擇剛剛安裝的 App
圖片來源: https://web-dev
- 會開啟 App 中的
target.html
頁面並顯示相關分享內容圖片來源: https://web-dev
站台連結: https://web-share.glitch.me/
喜歡這篇文章,請幫忙拍拍手喔 🤣