Skip to main content




Compartir en dispositivos móviles de forma sencilla con la API de destino de recurso compartido web


Updated

It appears in:
Applications Web progresivas

On a mobile device, sharing should be as simple as clicking the Share , elegir una aplicación y elegir con quién compartir. Por ejemplo, es posible que desee compartir un artículo interesante, ya be enviándolo por correo electrónico a sus amigos o twitteándolo al mundo.

En el pasado, solo las aplicaciones nativas podían registrarse en el sistema operativo para recibir recursos compartidos de otras aplicaciones instaladas. Pero con la API de destino compartido web, las aplicaciones web instaladas pueden registrarse con el sistema operativo subyacente como destino compartido para recibir contents compartido. Se agregó soporte para texto y datos en Chrome 71, y se agregó soporte para archivos en Chrome 76.

Web Share Target API es solo la mitad de la magia. Las aplicaciones web pueden compartir datos, archivos, enlaces o texto mediante la API Web Share. Consulte Compartir como un nativo para obtener más detalles.

wst-send-9725091

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

See Web Share Target in action

  1. With Chrome 76 or later (Android only), open the Web Share Target Demo.
  2. When prompted, click Install on pc to add the app to your home screen, or use the Chrome menu to add it to your home screen.
  3. Open any app that supports native sharing or use the Share button in the demo app.
  4. From the destination selector, choose Web sharing test.

After sharing, you should see all the shared information in the destination web application for web sharing.

Registre su aplicación como target para compartir

To register your app as a sharing target, you must meet Chrome installation criteria. Además, antes de que un Username pueda compartir su aplicación, debe agregarla a su pantalla de inicio. Esto evita que los sitios se agreguen al azar al selector de intención de compartir del usuario y garantiza que compartir sea algo que los usuarios quieran hacer con su aplicación.

Update your web application manifest

To register your app as a sharing destination, add a share_target entry to your web application manifest. This tells the operating system to include your application as an option in the intent selector. What you add to the manifest controls the data that your application will accept. There are three common scenarios for share_target
entry:

  • Accept basic information
  • Accept changes to the application
  • Accepting files

You can only have one share_target por manifiesto, si desea compartir en diferentes lugares dentro de su aplicación, proporcione eso como una opción dentro de la página de destino de destino para compartir.

Accept basic information

If your target app just accepts basic information like data, links, and text, add the following to the manifest.json proceedings:

"share_target": {
"action": "/share-target/",
"method": "GET",
"params": {
"title": "title",
"text": "text",
"url": "url"
}
}

Si su aplicación ya tiene un esquema de Url para compartir, puede reemplazar el param
values with your existing query parameters. For example, if your sharing url scheme uses body instead of text, could you replace "text": "text" with "text": "body".

the method the default is "GET" if not provided. the enctype field, which is not shown in this example, indicates the encoding type for the data. For him "GET" method, enctype default to "application / x-www-form-urlencoded" and it is ignored if it is configured for anything else.

Accept changes to the application

If the shared data changes the destination application in any way, for example, when saving a bookmark in the destination application, configure the method value for "POST" and includes the enctype countryside. The following example creates a bookmark in the target application, so it uses "POST" For him method and "multipart / form-data" For him
enctype:

{
"name": "Bookmark",
"share_target": {
"action": "/bookmark",
"method": "POST",
"enctype": "multipart / form-data",
"params": {
"url": "link"
}
}
}

Accepting files

As with application changes, accepting files requires that method to be "POST"
cast enctype to be. Further, enctype must be
"multipart / form-data"and a files an entry must be added.

You must also add a files An array that defines the types of files that your application accepts. The elements of the array are inputs with two members: a yam field and a accept
countryside. the accept El campo toma un tipo Mime, una extensión de archivo o una matriz que contiene ambos. Es mejor proporcionar una matriz que incluya tanto un tipo MIME como una extensión de archivo, ya que los sistemas operativos difieren en lo que prefieren.

{
"name": "Aggregator",
"share_target": {
"action": "/cgi-bin/aggregate",
"method": "POST",
"enctype": "multipart / form-data",
"params": {
"title": "name",
"text": "description",
"url": "link",
"files": [
{
"name": "records",
"accept": ["text/csv", ".csv"]
},
{
"name": "graphs",
"accept": "image/svg+xml"
}
]
}
}
}

Handle incoming content

How you handle incoming shared data is up to you and depends on your application. For example:

  • A client de correo electrónico podría redactar un nuevo correo electrónico utilizando title as the subject of an email, with text and url concatenated together like the body.
  • A social media app could compose a new post ignoring title, using
    text as the body of the message, and adding url how link. Yes text missing, the app could use url in the body as well. Yes url missing, the app can scan text looking for a url and add it as a link.
  • A photo sharing app could create a new slideshow using title as the title of the slideshow, text as a description, and files like the pictures in the slideshow.
  • A text messaging application could compose a new message using text and url
    concatenated together and dropping title.

GET action processing

If the user selects his application and his method it is "GET" (predeterminado), el browser abre una nueva ventana en el action URL. The browser then generates a query string using the URL encoded values provided in the manifest. For example, if the sharing application provides title and text, the query string is
?title=hello&text=world. To process this, use a DOMContentLoaded event listener on your foreground page and parse the query string:

window.addEventListener('DOMContentLoaded', () => {
const parsedUrl = new Url(window.location);
console.log('Title shared: ' + parsedUrl.searchParams.get('title'));
console.log('Text shared: ' + parsedUrl.searchParams.get('text'));
console.log('URL shared: ' + parsedUrl.searchParams.get('url'));
});

Be sure to hire a service worker to action page so that it loads quickly and works reliably, even if the user is offline.

Procesamiento de acciones POST

If you method it is "POST", such as if your target app accepts a saved bookmark or shared files, then the body of the entry POST The request contains the data transmitted by the application to share, encoded with the enctype value provided in manifest.

The foreground page cannot process this data directly. Since the page sees the data as a request, the page passes it to the service worker, where he can intercept it with a
fetch event listener. From here you can pass the data to the foreground page using postMessage () o páselo al server:

self.addEventListener('fetch', event => {
if (event.request.method !== 'POST') {
event.respondWith(fetch(event.request));
return;
}

event.respondWith((async () => {
const formData = await event.request.formData();
const link = formData.get('link') || '';
const responseUrl = await saveBookmark(link);
return Response.redirect(responseUrl, 303);
})());
});

Checking shared content

wst-receive-2698927

The destination app for sharing samples.

Make sure to check the incoming data. Unfortunately, there is no guarantee that other applications will share the appropriate content in the correct parameter.

For example, on Android, the url the field will be empty because it does not support Android shared system. Instead, the URLs will appear often in the text field, or occasionally in the title field.