让用户分享当前浏览的网站是一种常见的 Web 应用模式,您可以在许多新闻网站、博客或购物网站上看到这种模式。由于链接是网络的一项强大功能,因此我们希望从以下用户那里获得流量:在社交网站上看到分享链接的用户,或者在聊天消息中甚至通过电子邮件收到链接的用户。
使用 Web Share API
借助 Web Share API,用户可以分享数据,例如当前网页的网址,以及标题和描述性文字。Web Share API 的 navigator.share() 方法会调用设备的分享机制。它会返回一个 promise,并接受一个包含要分享的数据的实参。可能的值包括:
url:表示要分享的网址的字符串。text:表示要分享的文本的字符串。title:表示要分享的标题的字符串。可能会被浏览器忽略。
使用社交网站的分享 intent
并非所有浏览器都支持 Web Share API。因此,一种后备方案是与目标受众群体最常使用的社交网站集成。一个常见的示例是 Twitter,其 Web Intent 网址允许共享文本和网址。该方法通常包括制作网址并在浏览器中打开该网址。
界面注意事项
最佳实践是根据操作系统供应商的界面指南,使用平台既定的共享图标。
Windows 图标
Apple 图标
Android 和其他操作系统
采用渐进增强的方式
此代码段在支持 Web Share API 时使用该 API,否则会回退到 Twitter Web 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 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');
});