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!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.
