Permitir que el usuario comparta el sitio web en el que se encuentra es un patrón común de las apps web que puedes encontrar en muchos sitios de noticias, blogs o sitios de compras. Dado que la vinculación es uno de los superpoderes de la Web, el objetivo es adquirir tráfico de los usuarios que ven el vínculo compartido en los sitios de redes sociales o que lo reciben en mensajes de chat o incluso por correo electrónico.
Usa la API de Web Share
La API de Web Share permite que el usuario comparta datos como
la URL de la página en la que se encuentra, junto con un título y texto descriptivo.
El método navigator.share() de la API de Web Share invoca el mecanismo de uso compartido del dispositivo. Devuelve una promesa y toma un solo argumento con los datos que se compartirán. Los valores posibles son:
url: Es una cadena que representa la URL que se compartirá.text: Es una cadena que representa el texto que se compartirá.title: Es una cadena que representa un título que se compartirá. Es posible que el navegador lo ignore.
Usa el intent de uso compartido de un sitio de redes sociales
Aún no todos los navegadores admiten la API de Web Share. Por lo tanto, una alternativa es integrar los sitios de redes sociales más populares de tu público objetivo. Un ejemplo popular es Twitter, cuya URL de Web Intent permite compartir un texto y una URL. Por lo general, el método consiste en crear una URL y abrirla en un navegador.
Consideraciones sobre la IU
Es una práctica recomendada respetar el ícono para compartir establecido de la plataforma según los lineamientos de la IU de los proveedores del sistema operativo.
Ícono de Windows
Ícono de Apple
Android y otros sistemas operativos
Mejora progresiva
El fragmento usa la API de Web Share cuando es compatible y, luego, recurre a la URL de Web Intent de Twitter.
// 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');
});
Demostración
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');
});