사용자가 현재 웹사이트를 공유할 수 있도록 지원

사용자가 현재 보고 있는 웹사이트를 공유하도록 허용하는 것은 많은 뉴스 사이트, 블로그 또는 쇼핑 사이트에서 볼 수 있는 일반적인 웹 앱 패턴입니다. 링크는 웹의 강력한 기능 중 하나이므로 소셜 네트워킹 사이트에서 공유된 링크를 보거나 채팅 메시지 또는 일반적인 이메일로 링크를 받는 사용자로부터 트래픽을 확보할 수 있기를 바랍니다.

Web Share API 사용

Web Share API를 사용하면 사용자가 제목 및 설명 텍스트와 함께 현재 보고 있는 페이지의 URL과 같은 데이터를 공유할 수 있습니다. Web Share API의 navigator.share() 메서드는 기기의 공유 메커니즘을 호출합니다. 이 메서드는 프로미스를 반환하고 공유할 데이터가 포함된 단일 인수를 가져옵니다. 가능한 값은 다음과 같습니다.

  • url: 공유할 URL을 나타내는 문자열입니다.
  • text: 공유할 텍스트를 나타내는 문자열입니다.
  • title: 공유할 제목을 나타내는 문자열입니다. 브라우저에서 무시할 수 있습니다.

Browser Support

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

Source

소셜 네트워킹 사이트의 공유 인텐트 사용

일부 브라우저에서는 아직 Web Share API를 지원하지 않습니다. 따라서 대체 방법은 타겟층에서 가장 인기 있는 소셜 네트워킹 사이트와 통합하는 것입니다. 일반적인 예 는 텍스트와 URL을 공유할 수 있는 웹 인텐트 URL이 있는 트위터입니다. 이 메서드는 일반적으로 URL을 작성하고 브라우저에서 여는 것으로 구성됩니다.

UI 고려사항

운영체제 공급업체의 UI 가이드라인에 따라 플랫폼의 설정된 공유 아이콘을 준수하는 것이 좋습니다.

    Windows 아이콘

    Apple 아이콘

    Android 및 기타 운영체제

점진적 개선

이 스니펫은 Web Share API가 지원되는 경우 이를 사용한 다음 트위터 웹 인텐트 URL로 대체합니다.

// 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');
});

데모

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');
});