Giúp người dùng chia sẻ trang web mà họ đang truy cập

Cho phép người dùng chia sẻ trang web mà họ đang truy cập là một mẫu ứng dụng web phổ biến mà bạn có thể thấy trên nhiều trang tin tức, blog hoặc trang mua sắm. Vì việc liên kết là một trong những tính năng siêu việt của web, nên chúng tôi hy vọng sẽ thu hút được lưu lượng truy cập từ những người dùng nhìn thấy đường liên kết được chia sẻ trên các trang mạng xã hội hoặc nhận được đường liên kết đó trong tin nhắn trò chuyện hoặc thậm chí là email.

Sử dụng Web Share API

Web Share API cho phép người dùng chia sẻ dữ liệu như URL của trang mà họ đang truy cập, cùng với tiêu đề và văn bản mô tả. Phương thức navigator.share() của Web Share API sẽ gọi cơ chế chia sẻ của thiết bị. Phương thức này trả về một lời hứa và nhận một đối số duy nhất có dữ liệu cần chia sẻ. Các giá trị có thể là:

  • url: Chuỗi đại diện cho URL cần chia sẻ.
  • text: Chuỗi đại diện cho văn bản cần chia sẻ.
  • title: Chuỗi đại diện cho tiêu đề cần chia sẻ. Có thể bị trình duyệt bỏ qua.

Browser Support

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

Source

Sử dụng ý định chia sẻ của một trang mạng xã hội

Một số trình duyệt chưa hỗ trợ Web Share API. Do đó, bạn có thể tích hợp với các trang mạng xã hội phổ biến nhất của đối tượng mục tiêu. Một ví dụ phổ biến là Twitter, có URL Ý định web cho phép chia sẻ văn bản và URL. Phương thức này thường bao gồm việc tạo URL và mở URL đó trong trình duyệt.

Những điều cần cân nhắc về giao diện người dùng

Bạn nên tuân thủ biểu tượng chia sẻ đã thiết lập của nền tảng theo nguyên tắc về giao diện người dùng của nhà cung cấp hệ điều hành.

    Biểu tượng Windows

    Biểu tượng Apple

    Android và các hệ điều hành khác

Cải tiến tăng dần

Đoạn mã này sử dụng Web Share API khi được hỗ trợ, sau đó quay lại URL Ý định web của 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 isMac = navigator.platform.toLowerCase().includes('mac');

// Find out if the user is on a Windows device.
const isWin = navigator.platform.toLowerCase().includes('win');

// For Apple devices or Windows, use the platform-specific share icon.
icon.classList.add(`share${isMac? 'mac' : (isWin? '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.
  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');
});

Bản minh hoạ

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;
    background: #9c9c9c;
    padding: 12px;
    color:  #fff;
    border: 1px solid #9c9c9c;
    border-radius: 8px;
}

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

button:hover {
  background: #5089d3ff;
}

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

.share {
  background-image: url('windows.svg');
  color: #fff;
}

.sharemac {
  background-image: url('mac.svg');
  color: #fff;
}
        

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 isMac = navigator.platform.toLowerCase().includes('mac');

// Find out if the user is on a Windows device.
const isWin = navigator.platform.toLowerCase().includes('win');

// For Apple devices or Windows, use the platform-specific share icon.
icon.classList.add(`share${isMac? 'mac' : (isWin? '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.
  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');
});