# Web Share API
## 概述
網頁內容如果要分享到其他應用,通常要自己實現分享接口,逐一給出目標應用的連接方式。這樣很麻煩,也對網頁性能有一定影響。Web Share API 就是為了解決這個問題而提出的,允許網頁調用操作系統的分享接口,實質是 Web App 與本機的應用程序交換信息的一種方式。
這個 API 不僅可以改善網頁性能,而且不限制分享目標的數量和類型。社交媒體應用、電子郵件、即時消息、以及本地系統安裝的、且接受分享的應用,都會出現在系統的分享彈窗,這對手機網頁尤其有用。另外,使用這個接口只需要一個分享按鈕,而傳統的網頁分享有多個分享目標,就有多少個分享按鈕。
目前,桌面的 Safari 瀏覽器,手機的安卓 Chrome 瀏覽器和 iOS Safari 瀏覽器,支持這個 API。
這個 API 要求網站必須啟用 HTTPS 協議,但是本地 Localhost 開發可以使用 HTTP 協議。另外,這個 API 不能直接調用,只能用來響應用戶的操作(比如`click`事件)。
## 接口細節
該接口部署在`navigator.share`,可以用下面的代碼檢查本機是否支持該接口。
```javascript
if (navigator.share) {
// 支持
} else {
// 不支持
}
```
`navigator.share`是一個函數方法,接受一個配置對象作為參數。
```javascript
navigator.share({
title: 'WebShare API Demo',
url: 'https://codepen.io/ayoisaiah/pen/YbNazJ',
text: '我正在看《Web Share API》'
})
```
配置對象有三個屬性,都是可選的,但至少必須指定一個。
- `title`:分享文檔的標題。
- `url`:分享的 URL。
- `text`:分享的內容。
一般來說,`url`是當前網頁的網址,`title`是當前網頁的標題,可以采用下面的寫法獲取。
```javascript
const title = document.title;
const url = document.querySelector('link[rel=canonical]') ?
document.querySelector('link[rel=canonical]').href :
document.location.href;
```
`navigator.share`的返回值是一個 Promise 對象。這個方法調用之后,會立刻彈出系統的分享彈窗,用戶操作完畢之后,Promise 對象就會變為`resolved`狀態。
```javascript
navigator.share({
title: 'WebShare API Demo',
url: 'https://codepen.io/ayoisaiah/pen/YbNazJ'
}).then(() => {
console.log('Thanks for sharing!');
}).catch((error) => {
console.error('Sharing error', error);
});
```
由于返回值是 Promise 對象,所以也可以使用`await`命令。
```javascript
shareButton.addEventListener('click', async () => {
try {
await navigator.share({ title: 'Example Page', url: '' });
console.log('Data was shared successfully');
} catch (err) {
console.error('Share failed:', err.message);
}
});
```
## 分享文件
這個 API 還可以分享文件,先使用`navigator.canShare()`方法,判斷一下目標文件是否可以分享。因為不是所有文件都允許分享的,目前圖像,視頻,音頻和文本文件可以分享2。
```javascript
if (navigator.canShare && navigator.canShare({ files: filesArray })) {
// ...
}
```
上面代碼中,`navigator.canShare()`方法的參數對象,就是`navigator.share()`方法的參數對象。這里的關鍵是`files`屬性,它的值是一個`FileList`實例對象。
`navigator.canShare()`方法返回一個布爾值,如果為`true`,就可以使用`navigator.share()`方法分享文件了。
```javascript
if (navigator.canShare && navigator.canShare({ files: filesArray })) {
navigator.share({
files: filesArray,
title: 'Vacation Pictures',
text: 'Photos from September 27 to October 14.',
})
.then(() => console.log('Share was successful.'))
.catch((error) => console.log('Sharing failed', error));
}
```
## 參考鏈接
- [How to Use the Web Share API](https://css-tricks.com/how-to-use-the-web-share-api/), Ayooluwa Isaiah
- [Web Share API - Level 1](https://wicg.github.io/web-share/), W3C
- [Introducing the Web Share API](https://developers.google.com/web/updates/2016/09/navigator-share), Paul Kinlan, Sam Thorogood
- [Share like a native app with the Web Share API](https://web.dev/web-share/), Joe Medley