วิธีให้ผู้ใช้แชร์เว็บไซต์ที่เข้าชม

การอนุญาตให้ผู้ใช้แชร์เว็บไซต์ที่กำลังเข้าชมเป็นรูปแบบทั่วไปของเว็บแอปที่คุณพบได้ในเว็บไซต์ข่าวสาร บล็อก หรือเว็บไซต์ช็อปปิ้งหลายแห่ง เนื่องจากการลิงก์เป็นหนึ่งในความสามารถที่ยอดเยี่ยมของเว็บ จึงหวังว่าจะได้รับผู้เข้าชมจากผู้ใช้ที่เห็นลิงก์ที่แชร์ในเว็บไซต์โซเชียลเน็ตเวิร์ก หรือผู้ใช้ที่ได้รับลิงก์ผ่านข้อความแชทหรือแม้แต่ผ่านอีเมลแบบเดิมๆ

วิธีที่ทันสมัย

การใช้ Web Share API

Web Share API ช่วยให้ผู้ใช้แชร์ข้อมูล เช่น URL ของหน้าที่กำลังเข้าชม พร้อมกับชื่อและข้อความอธิบาย เมธอด navigator.share() ของ Web Share API จะเรียกใช้กลไกการแชร์ดั้งเดิมของอุปกรณ์ โดยจะแสดงผล Promise และรับอาร์กิวเมนต์เดียวที่มีข้อมูลที่จะแชร์ ค่าที่เป็นไปได้มีดังนี้

  • url: สตริงที่แสดง URL ที่จะแชร์
  • text: สตริงที่แสดงข้อความที่จะแชร์
  • title: สตริงที่แสดงชื่อที่จะแชร์ เบราว์เซอร์อาจไม่สนใจ

Browser Support

  • Chrome: 128.
  • Edge: 93.
  • Firefox: behind a flag.
  • Safari: 12.1.

Source

วิธีแบบคลาสสิก

การใช้ Intent ในการแชร์ของเว็บไซต์โซเชียลเน็ตเวิร์ก

เบราว์เซอร์บางรายการยังไม่รองรับ Web Share API ดังนั้นวิธีสำรองคือการผสานรวมกับเว็บไซต์โซเชียลเน็ตเวิร์กยอดนิยมที่สุดของกลุ่มเป้าหมาย ตัวอย่างที่ได้รับความนิยม คือ Twitter ซึ่ง URL ของ Web Intent อนุญาตให้แชร์ข้อความและ URL ได้ โดยปกติแล้ววิธีนี้จะประกอบด้วยการสร้าง URL และเปิด URL ในเบราว์เซอร์

ข้อควรพิจารณาเกี่ยวกับ UI

การใช้ไอคอนแชร์ที่แพลตฟอร์มกำหนดไว้ตามหลักเกณฑ์ UI ของผู้ให้บริการระบบปฏิบัติการถือเป็นเรื่องที่ควรทำ

  • Windows:
  • Apple:
  • Android และระบบปฏิบัติการอื่นๆ:

การเพิ่มประสิทธิภาพแบบต่อเนื่อง

ข้อมูลโค้ดด้านล่างใช้ Web Share API เมื่อระบบรองรับ จากนั้นจะกลับไปใช้ URL ของ Web Intent ของ 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');
});