桓桓鄉寇

手機版分享按鈕實作: navigator.share() API

最近接觸了一個案子,在設計稿中,手機版的導覽選單有一個「分享」按鈕,但是設計師並未指定是要透過什麼方式分享,因此我便提議使用 navigator.share 這個 API 來製作。

這個 API 的實際效果如下圖所示:

基本語法

const sharePromise = navigator.share(data);

navigator.share 這個 API 中,data 是包含四種資料的物件:

在這次的情境下,並不會使用到 file。有關分享檔案的作法,我目前也還沒有嘗試過,因此未來測試後再補上。

必須注意的是,使用這個 API 的網址必須為 HTTPS 版本,如果是 HTTP 版本,則會出現錯誤。

實作語法

const shareData = {
    title: document.title,
    text: '我想與你分享' + document.title + '的精彩內容!',
    url: document.location.href,
}, btn = document.querySelector('#footer-share-btn');

btn.addEventListener('click', async () => {
  try {
    await navigator.share(shareData)
  } catch(err) {
    console.log( 'Error: ' + err );
  }
});

這裡使用的 URL 是 document.location.href,不過根據這篇文章的說法,建議在實作時應該使用標準網址 (Canonical URL),避免因為擷取到當前頁面的行動裝置版網址,導致使用桌上型裝置時體驗不佳。

實作下來的結果如下 (僅手機版適用)。

See the Pen by Eric Chuang (@eric-chuang) on CodePen.

參考資料

Exit mobile version