如何讓使用者分享自己瀏覽的網站

讓使用者分享他們造訪的網站屬於常見的網頁應用程式模式,您可以在許多新聞網站、網誌或購物網站上找到這些模式。因為連結是網路的一項超強功能,希望吸引到的使用者在社交網站上看到分享連結、透過即時通訊訊息或純粹的舊學校收到連結的使用者。

現代做法

使用 Web Share API

Web Share API 可讓使用者分享所在網頁網址等資料,以及標題和說明文字。Web Share API 的 navigator.share() 方法會叫用裝置的原生共用機制。此方法會傳回一個承諾,並使用一個具有待共用資料的引數。可能的值為:

  • url:代表要共用網址的字串。
  • text:代表要共用文字的字串,
  • title:代表要分享的標題的字串。瀏覽器可能會忽略這個元素。

瀏覽器支援

  • 89
  • 93
  • 12.1

資料來源

經典風格

使用社群網站的分享意圖

目前並非所有瀏覽器都支援 Web Share API。因此,備用方案可與目標對像中最熱門的社群網站整合。有個熱門的例子是 Twitter,這個 Twitter 的網路意圖網址允許分享文字和網址。這個方法通常包含製作網址,並在瀏覽器中開啟。

使用者介面注意事項

這個做法非常適合遵循作業系統廠商的 UI 指南,遵循平台已建立的共用圖示。

  • Windows:
  • Apple:
  • Android 和其他作業系統:

漸進式增強

下方的程式碼片段在支援時使用 Web Share API,然後改回使用 Twitter 的網路意圖網址。

// DOM references
const button = document.querySelector('button');
const icon = button.querySelector('.icon');
const canonical = document.querySelector('link[rel="canonical"]');

// Find out if the user is on a device made by Apple.
const IS_MAC = /Mac|iPhone/.test(navigator.platform);
// Find out if the user is on a Windows device.
const IS_WINDOWS = /Win/.test(navigator.platform);
// For Apple devices or Windows, use the platform-specific share icon.
icon.classList.add(`share${IS_MAC? 'mac' : (IS_WINDOWS? 'windows' : '')}`);

button.addEventListener('click', async () => {
  // Title and text are identical, since the title may actually be ignored.
  const title = document.title;
  const text = document.title;
  // Use the canonical URL, if it exists, else, the current location.
  const url = canonical?.href || location.href;

  // Feature detection to see if the Web Share API is supported.
  if ('share' in navigator) {
    try {
      await navigator.share({
        url,
        text,
        title,
      });
      return;
    } catch (err) {
      // If the user cancels, an `AbortError` is thrown.
      if (err.name !== "AbortError") {
        console.error(err.name, err.message);
      }
    }
  }
  // Fallback to use Twitter's Web Intent URL.
  // (https://developer.twitter.com/en/docs/twitter-for-websites/tweet-button/guides/web-intent)
  const shareURL = new URL('https://twitter.com/intent/tweet');
  const params = new URLSearchParams();
  params.append('text', text);
  params.append('url', url);
  shareURL.search = params;
  window.open(shareURL, '_blank', 'popup,noreferrer,noopener');
});

其他資訊

操作示範

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>How to let the user share the website they are on</title>
    <link rel="stylesheet" href="style.css" />
    <!-- TODO: Devsite - Removed inline handlers -->
    <!-- <script src="script.js" defer></script> -->
  </head>
  <body>
    <h1>How to let the user share the website they are on</h1>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at libero
      eget ante congue molestie. Integer varius enim leo. Duis est nisi,
      ullamcorper et posuere eu, mattis sed lorem. Lorem ipsum dolor sit amet,
      consectetur adipiscing elit. In at suscipit erat, et sollicitudin lorem.
    </p>
    <img src="https://placekitten.com/400/300" width=400 height=300>
    <p>
      In euismod ornare scelerisque. Nunc imperdiet augue ac porttitor
      porttitor. Pellentesque habitant morbi tristique senectus et netus et
      malesuada fames ac turpis egestas. Curabitur eget pretium elit, et
      interdum quam.
    </p>
    <hr />
    <button type="button"><span class="icon"></span>Share</button>
  </body>
</html>

CSS


        :root {
  color-scheme: dark light;
}

html {
  box-sizing: border-box;
}

*, *:before, *:after {
  box-sizing: inherit;
}

body {
  margin: 1rem;
  font-family: system-ui, sans-serif;
}

img,
video {
  height: auto;
  max-width: 100%;
}

button {
  display: flex;
}

button .icon {
  display: inline-block;
  width: 1em;
  height: 1em;
  background-size: 1em;
}

@media (prefers-color-scheme: dark) {
  button .icon {
    filter: invert();
  }
}

.share {
  background-image: url('share.svg');
}

.sharemac {
  background-image: url('sharemac.svg');
}
        

JS


        // DOM references
const button = document.querySelector('button');
const icon = button.querySelector('.icon');
const canonical = document.querySelector('link[rel="canonical"]');

// Find out if the user is on a device made by Apple.
const IS_MAC = /Mac|iPhone/.test(navigator.platform);
// Find out if the user is on a Windows device.
const IS_WINDOWS = /Win/.test(navigator.platform);
// For Apple devices or Windows, use the platform-specific share icon.
icon.classList.add(`share${IS_MAC? 'mac' : (IS_WINDOWS? 'windows' : '')}`);

button.addEventListener('click', async () => {
  // Title and text are identical, since the title may actually be ignored.
  const title = document.title;
  const text = document.title;
  // Use the canonical URL, if it exists, else, the current location.
  const url = canonical?.href || location.href;

  // Feature detection to see if the Web Share API is supported.
  if ('share' in navigator) {
    try {
      await navigator.share({
        url,
        text,
        title,
      });
      return;
    } catch (err) {
      // If the user cancels, an `AbortError` is thrown.
      if (err.name !== "AbortError") {
        console.error(err.name, err.message);
      }
    }
  }
  // Fallback to use Twitter's Web Intent URL.
  // (https://developer.twitter.com/en/docs/twitter-for-websites/tweet-button/guides/web-intent)
  const shareURL = new URL('https://twitter.com/intent/tweet');
  const params = new URLSearchParams();
  params.append('text', text);
  params.append('url', url);
  shareURL.search = params;
  window.open(shareURL, '_blank', 'popup,noreferrer,noopener');
});