به کاربران کمک کنید وب‌سایتی را که در آن هستند به اشتراک بگذارند

اجازه دادن به کاربر برای به اشتراک گذاشتن وب‌سایتی که در آن قرار دارد، یک الگوی رایج در برنامه‌های وب است که می‌توانید در بسیاری از سایت‌های خبری، وبلاگ‌ها یا سایت‌های خرید پیدا کنید. از آنجایی که لینک دادن یکی از قدرت‌های فوق‌العاده وب است، امید این است که از کاربرانی که لینک به اشتراک گذاشته شده را در سایت‌های شبکه‌های اجتماعی می‌بینند، یا آن را در پیام‌های چت یا حتی ایمیل‌های ساده دریافت می‌کنند، ترافیک جذب شود.

استفاده از API اشتراک‌گذاری وب

API اشتراک‌گذاری وب به کاربر اجازه می‌دهد داده‌هایی مانند URL صفحه‌ای که در آن قرار دارد را به همراه عنوان و متن توصیفی به اشتراک بگذارد. متد navigator.share() از API اشتراک‌گذاری وب، مکانیزم اشتراک‌گذاری دستگاه را فراخوانی می‌کند. این متد یک promise را برمی‌گرداند و یک آرگومان واحد با داده‌هایی که قرار است به اشتراک گذاشته شوند، دریافت می‌کند. مقادیر ممکن عبارتند از:

  • url : رشته‌ای که نشان‌دهنده‌ی URL مورد نظر برای اشتراک‌گذاری است.
  • text : رشته‌ای که نشان‌دهنده متنی است که قرار است به اشتراک گذاشته شود.
  • title : رشته‌ای که عنوانی را که قرار است به اشتراک گذاشته شود نشان می‌دهد. ممکن است توسط مرورگر نادیده گرفته شود.

Browser Support

  • کروم: ۱۲۸.
  • لبه: ۹۳.
  • فایرفاکس: پشت یک پرچم.
  • سافاری: ۱۲.۱.

Source

از هدف اشتراک‌گذاری یک سایت شبکه اجتماعی استفاده کنید

هنوز همه مرورگرها از Web Share API پشتیبانی نمی‌کنند. بنابراین، یک راه حل جایگزین، ادغام با محبوب‌ترین سایت‌های شبکه اجتماعی مخاطبان هدف شماست. یک مثال محبوب توییتر است که URL هدف وب آن امکان اشتراک‌گذاری یک متن و یک URL را فراهم می‌کند. این روش معمولاً شامل ایجاد یک URL و باز کردن آن در یک مرورگر است.

ملاحظات رابط کاربری

بهترین روش این است که به آیکون اشتراک‌گذاریِ تعیین‌شده‌ی پلتفرم، مطابق با دستورالعمل‌های رابط کاربریِ فروشندگان سیستم عامل، احترام بگذارید.

    آیکون ویندوز

    آیکون اپل

    اندروید و سایر سیستم عامل ها

بهبود تدریجی

این قطعه کد در صورت پشتیبانی از 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');
});

نسخه آزمایشی

اچ‌تی‌ام‌ال

<!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>

سی‌اس‌اس


        :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;
}
        

جی‌اس


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