前端

How Smart Tools Are Shaping the Future of Creative Work

Eric Chuang
2021-06-30

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

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

基本語法

const sharePromise = navigator.share(data);

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

  • url 是 USVString 字串,代表欲分享的網址。USVString 與一般的 DOMString 字串最主要的差異在 USVString 不能包含輔助平面字元 (surrogate code points),藉此讓使用者代理程式在將字串序列化的過程中,不會產生替代字元 (�)。
  • text 是 USVString 字串,分享連結時,附帶的文字敘述。
  • title 是 USVString 字串,代表分享連結時附帶的標題。根據 W3C 的說法,裝置有可能會忽略這個值,目前自己測試還沒有看到呈現的樣子。
  • file 是欲分享的檔案所組成的陣列。

在這次的情境下,並不會使用到 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.

參考資料

Sign up for our newsletter

Subscribe to our newsletter to receive the latest updates, expert insights, and practical tips directly in your inbox. Stay informed with content designed to help you grow.

+480.000 happy customers

Gain more with expert solutions

Unlock the full potential of your business with our expert solutions. Our team provides tailored strategies, professional guidance, and actionable insights to help you achieve better results.

  • Eric Chuang
  • •
  • 2025-01-23
如何同時使用 Webinoly 與 Cloudflare 保護網站安全

在社群夥伴勇哥的文章〈Webinoly 最新版快速安裝〉中,提到使用 Webinoly 來建立 WordPre […]

主機