사용자가 현재 사용 중인 웹사이트를 공유할 수 있도록 하는 방법

사용자가 자신이 있는 웹사이트를 공유하도록 허용하는 것은 여러 뉴스 사이트, 블로그 또는 쇼핑 사이트에서 찾을 수 있는 일반적인 웹 앱 패턴입니다. 연결은 웹의 초능력 중 하나이므로 소셜 네트워킹 사이트에서 공유 링크를 보는 사용자나 채팅 메시지, 심지어 이메일을 통해 공유 링크를 받는 사용자의 트래픽을 획득하는 것이 희망입니다.

현대적인 방식

Web Share API 사용

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

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

브라우저 지원

  • 89
  • 93
  • 12.1

소스

기존의 방식

소셜 네트워크 사이트의 공유 의도 사용

일부 브라우저에서는 아직 Web Share API를 지원하지 않습니다. 따라서 대체는 타겟 잠재고객의 가장 인기 있는 소셜 네트워킹 사이트와 통합하는 것입니다. Twitter는 웹 인텐트 URL을 통해 텍스트와 URL의 공유를 허용합니다. 이 메서드는 일반적으로 URL을 만들고 브라우저에서 여는 것으로 구성됩니다.

UI 고려사항

운영체제 공급업체의 UI 가이드라인에 따라 플랫폼에 설정된 공유 아이콘을 존중하는 것은 좋은 터치입니다.

  • Windows:
  • 사과:
  • Android 및 기타 운영체제:

점진적 개선

아래 스니펫은 지원되는 경우 Web Share API를 사용하고 Twitter의 웹 인텐트 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 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');
});