Skip to main content




Las aplicaciones Web pueden utilizar las mismas capacidades de uso compartido proporcionadas por el sistema que las aplicaciones nativas.


Updated

With the API Web Share, las aplicaciones web pueden utilizar las mismas capacidades de uso compartido proporcionadas por el sistema que las aplicaciones nativas. La API Web Share hace posible que las aplicaciones web compartan enlaces, texto y archivos con otras aplicaciones instaladas en el dispositivo de la misma manera que las aplicaciones nativas.

Sharing is only half the magic. Web applications can also be shared targets, which means that they can receive data, links, text, and files from native or web applications. See the Receive Shared Data post for details on registering your app as a sharing destination.

Concepts and usage

wst-send-2631807

System level shared destination selector with a PWA installed as an option.

Capabilities and limitations

The web share has the following capabilities and limitations:

  • Solo se puede usar en un sitio que admita HTTPS.
  • Debe invocarse en respuesta a una acción del Username, como un clic. Invocándolo a través del onload the handler is impossible.
  • Puede compartir Url, texto o archivos.
  • As of mid-2020, it is only available in Safari and on Android on Chromium forks. See
    MDN
    for details.

To share links and text, use the Compartir() método, que es un método basado en promesas con un objeto de propiedades requerido. Para evitar que el browser arroje un TypeError, the object must contain at least one of the following properties: title, text, url or files. You can, for example, share text without a URL or vice versa. Allow all three members to extend the flexibility of use cases. Imagine if after running the following code, the user chose an email application as the destination. the title The parameter can become the subject of the email, the text, the body of the message and the files, the attachments.

if (navigator.Compartir) {
navigator.Compartir({
title: 'web.dev',
text: 'Check out web.dev.',
url: 'https://web.dev/',
})
.then(() => console.log('Successful share'))
.catch((error) => console.log('Error sharing', error));
}

Si su sitio tiene varias URL para el mismo contents, comparta la URL canónica de la página en lugar de la URL actual. En lugar de compartir
document.location.href, you should look for a canonical url label on page y comparte eso. Esto proporcionará una mejor experiencia al usuario. No solo evita las redirecciones, sino que también garantiza que una URL compartida proporcione la user experience correcta para un client en particular. Por ejemplo, si un amigo comparte una URL móvil y la miras en una computadora de escritorio, deberías ver una versión de escritorio:

let url = document.location.href;
const canonicalElement = document.querySelector('link[rel=canonical]');
if (canonicalElement !== null) {
url = canonicalElement.href;
}
navigator.Compartir({url: url});

Share files

To share files, first try and call navigator.canShare (). Then include an array of files in the call to navigator.share ():

if (navigator.canShare && navigator.canShare({ files: filesArray })) {
navigator.Compartir({
files: filesArray,
title: 'Vacation Pictures',
text: 'Photos from September 27 to October 14.',
})
.then(() => console.log('Share was successful.'))
.catch((error) => console.log('Sharing failed', error));
} else {
console.log(`Your system doesn't support sharing files.`);
}

Notice that the sample handles feature detection by testing
naviagator.canShare () instead of for navigator.share (). The data object passed to canShare () only admit the files property. Image, video, audio and text files can be shared. (See
File extensions allowed in Chromium.) More types of files may be added in the future.

Santa Tracker Case Study

santa-phone-7657103

Santa Tracker share button.

Santa tracker, un proyecto de Open Source, es una tradición navideña en Google. Cada diciembre, puedes celebrar la temporada con juegos y experiencias educativas.

In 2016, the Santa Tracker team used the Web Share API on Android. This API was perfect for mobile devices. In previous years, the team disabled sharing buttons on mobile devices because space is tight and they couldn't justify having multiple sharing goals.

But with the Web Share API, they were able to present just one button, saving valuable pixels. They also found that users shared with Web Share about 20% more than users without the API enabled. Go to
Santa tracker to see Web Share in action.

Web sharing demos