It seems to have been obscured since Chrome 61 for Android first launched its Web Sharing API. In fact, it provides a way to trigger a native sharing dialog for the device (the desktop if using Safari) when sharing content directly from a website or web application (such as a link or contact card).
While users can already share content from web pages in native ways, they must find the option in the browser menu, and even then, there is no control over the shared content. The introduction of this API allows developers to add sharing capabilities to applications or websites by leveraging native content sharing capabilities on user devices.
This method has many advantages over the traditional method:
- Users have a wider range of content sharing options than the limited number of options you may have in your DIY implementation.
- By canceling third-party scripts from various social platforms, you can reduce page loading time.
- You don't need to add a series of buttons to different social media sites and emails. The native sharing option of the device is triggered with just one button.
- Users can customize their preferred shared targets on their devices without being limited to predefined options.
Browser support instructions
Before we go into detail about how API works, let's solve the problem of browser support. To be honest, the browser support is not ideal at present. It only works with Chrome for Android and Safari (Desktop and iOS).
This browser supports data from Caniuse, which contains more details. The number indicates that the browser supports this feature in this version and later.
Desktop
Mobile/Tablet PC
But don't be discouraged by this, don't adopt this API on your website. As you will see, implementing a fallback to a browser that does not support it is very easy.
Some requirements for using API
Before you can adopt this API on your own web project, there are two things to note:
- Your website must be provided via HTTPS. For local development, the API works as well when your site runs on localhost.
- To prevent abuse, the API can only trigger in response to certain user actions, such as click events.
Example
To demonstrate how to use this API, I prepared a demo that works basically the same as my website. Here is how it looks:
Currently, after clicking the share button, a dialog box will pop up showing some options for sharing content. Here is the part of the code that helps us achieve this:
<code>shareButton.addEventListener('click', event => { shareDialog.classList.add('is-open'); });</code>
Let's move on to convert this example to using the Web Sharing API. The first thing to do is check whether the API is indeed supported by the user's browser, as shown below:
<code>if (navigator.share) { // 支持Web 共享API } else { // 回退}</code>
Using a Web Sharing API is as simple as calling navigator.share()
method and passing an object that contains at least one of the following fields:
-
url
: A string representing the URL to be shared. This is usually a document URL, but not necessarily. You can share any URL through the Web Sharing API. -
title
: A string representing the title to be shared, usuallydocument.title
. -
text
: Any text you want to include.
Here is what it looks like in actual application:
<code>shareButton.addEventListener('click', event => { if (navigator.share) { navigator.share({ title: 'WebShare API Demo', url: 'https://codepen.io/ayoisaiah/pen/YbNazJ' }).then(() => { console.log('Thanks for sharing!'); }) .catch(console.error); } else { // 回退} });</code>
At this point, once the share button is clicked in the supported browser, the native selector will pop up all possible targets that users can share data. The goal can be a social media app, email, instant messaging, text messages, or other registered shared target.
The API is based on Promise, so you can attach the .then()
method to display the shared successful message and use .catch()
to handle the error. In a real-life scenario, you may want to use the following code snippet to get the title and URL of the page:
<code>const title = document.title; const url = document.querySelector('link[rel=canonical]') ? document.querySelector('link[rel=canonical]').href : document.location.href;</code>
For URLs, we first check if the page has a canonical URL, and if so, use that URL. Otherwise, we get href
from document.location
.
It's a good idea to provide a fallback
In browsers that do not support the Web Sharing API, we need to provide a fallback mechanism so that users on these browsers can still get some sharing options.
In our case, we have a pop-up dialog with some options to share content, and the buttons in our demo aren't actually linked to anywhere, because, well, it's just a demo. However, if you want to know how to create your own link to share a webpage without a third-party script, Adam Coti’s article is a great place to start.
What we want to do is display a fallback dialog for users of browsers that do not support the Web Sharing API. It's as simple as moving the code that opens a shared dialog into else
block:
<code>shareButton.addEventListener('click', event => { if (navigator.share) { navigator.share({ title: 'WebShare API Demo', url: 'https://codepen.io/ayoisaiah/pen/YbNazJ' }).then(() => { console.log('Thanks for sharing!'); }) .catch(console.error); } else { shareDialog.classList.add('is-open'); } });</code>
Now, no matter what browser the user uses, all users are covered. Here is a comparison of how the share button behaves on two mobile browsers, one supports the Web Sharing API and the other does not:
Try it! Use browsers that support web sharing and unsupported browsers. It should be similar to the above demonstration.
Summarize
This covers almost all the basics you need to know about the Web Sharing API. By implementing it on your website, visitors can more easily share your content through various social networks, contacts, and other native applications.
It is also worth noting that if your web application meets the progressive web application installation criteria and is added to the user's home screen, you can add it as a shared target. This is a feature that you can read about the Web Share Target API on Google Developers.
Although browser support is jagged, fallbacks are easy to implement, so I don't think there is any reason more websites don't adopt it. If you want to learn more about this API, you can read the specification here.
Have you used the Web Sharing API? Please share your experience in the comments.
The above is the detailed content of How to Use the Web Share API. For more information, please follow other related articles on the PHP Chinese website!

If you've ever had to display an interactive animation during a live talk or a class, then you may know that it's not always easy to interact with your slides

With Astro, we can generate most of our site during our build, but have a small bit of server-side code that can handle search functionality using something like Fuse.js. In this demo, we’ll use Fuse to search through a set of personal “bookmarks” th

I wanted to implement a notification message in one of my projects, similar to what you’d see in Google Docs while a document is saving. In other words, a

Some months ago I was on Hacker News (as one does) and I ran across a (now deleted) article about not using if statements. If you’re new to this idea (like I

Since the early days of science fiction, we have fantasized about machines that talk to us. Today it is commonplace. Even so, the technology for making

I remember when Gutenberg was released into core, because I was at WordCamp US that day. A number of months have gone by now, so I imagine more and more of us

The idea behind most of web applications is to fetch data from the database and present it to the user in the best possible way. When we deal with data there

Let's do a little step-by-step of a situation where you can't quite do what seems to make sense, but you can still get it done with CSS trickery. In this


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.