允许用户共享他们所在的网站是一种常见的 Web 应用模式,许多新闻网站、博客或购物网站都可以采用这种模式。由于链接是网络的超能力之一,因此我们希望吸引那些在社交网站上看到分享链接的用户,或者通过聊天消息收到分享链接或者通过电子邮件收到分享链接的用户获得流量。
现代方式
使用 Web Share API
利用 Web Share API,用户可分享自己所在网页的网址等数据,以及标题和说明性文字。Web Share API 的 navigator.share()
方法会调用设备的原生共享机制。它会返回一个 promise,并接受包含要共享的数据的单个参数。可能的值包括:
url
:一个字符串,表示要共享的网址。text
:表示要共享的文本的字符串。title
:表示要分享的标题的字符串。可能会被浏览器忽略。
经典方法
使用社交网站的分享 intent
并非所有浏览器都支持 Web Share API。因此,回退方法是与目标受众群体最受欢迎的社交网站集成。一个热门的例子是 Twitter,其网络意图网址允许分享文本和网址。该方法通常涉及编写网址并在浏览器中打开网址。
界面注意事项
最好按照操作系统供应商的界面指南遵循平台既定的分享图标。
- Windows:
- Apple:
- Android 和其他操作系统:
渐进增强
以下代码段会在支持的情况下使用 Web Share API,然后回退到 Twitter 的网络 intent 网址。
// 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');
});