当前位置:网站首页>Share API on the web

Share API on the web

2020-11-08 23:46:00 Dunib

In my submission Web Share API Very cool , In short , It will take advantage of native sharing features on the platform you are using ( If the platform supports ).

I like this one :

 stay iOS On the active Web Share API

It's more than that :

Why? ?

  • Web Share API Just a few lines of code . Simple ! There are no images , There's no heavyweight JavaScript or iframe.
  • What users see UI It's customized for its platform , It may even be customized by them , To include in it what they want .

good job ,Web standard .

But not all places support . for example , I am here Chrome Write this blog post in the browser , On the desktop Chrome Cannot be used in the browser , But on the desktop Safari But it can work

therefore , If I'm going to use it , I'd rather test whether the button supports . It's very simple :

if (navigator.share) {

}

Here is an example , If API If supported , I'll take one <button> Put it on the article ,HTML and CSS Omit .

Safari Browser effect ,Chrome I won't support it

JavaScript Did some fancy moves to get the title and the first paragraph of the article , In order to be in API Use in . I like Jeremy Keith What you do on the page :

if (navigator.share) {
  navigator.share(
    {
      title: document.querySelector('title').textContent,
      text: document.querySelector('meta[name="description"]').getAttribute('content'),
      url: document.querySelector('link[rel="canonical"]').getAttribute('href')
    }
  );
}

You can also pass strings to these values , It's just showing you how to do something dynamically on any page .

Jeremy And has been advocating the establishment of a JavaScript Optional Web Share API edition , He thinks it's possible to work like this .

<button type="share">

then , Specify the title and text :

<button type="share" value="title,text">

It's a bit fashionable for me to use commas , What if the title contains commas ? The designation URL Well ? Can we divide them all into attributes ? I think I know Jeremy What would you say : This is a simple declarative version , If you want to change the default behavior , That's it JavaScript The role of .

How to use Web Share API

Since the Android Of Chrome 61 Since its first introduction ,Web Share API It seems to have caught attention . essentially , It provides a way , When directly from the website or Web When applications share content , Can trigger the device ( Or desktop , If you use Safari) Local sharing dialog box for , For example, links or contact cards .

Although users have been able to share the content of a web page in a native way , But they have to find this option in the browser menu , Even so , You can't control what you share . The API The introduction of the new technology allows developers to take advantage of native content sharing capabilities on user devices , Add sharing to your app or website .

iOS Provides many native sharing options

Compared with the traditional method , This approach has many advantages :

  • With you in DIY There is a limited amount of content that may be in the implementation compared to , Users will get a wide range of content sharing options .
  • You can reduce page loading time by deleting third-party scripts from various social platforms .
  • You don't need to add a series of buttons to different social media sites and emails , One button is enough to trigger the device's native sharing option .
  • Users can customize their favorite sharing goals on their own devices , It's not limited to predefined options .

About browser support

Introducing API Before the details of the work , Let's solve the problem of browser support first . Tell the truth , The current browser support is not high . It only applies to Android edition Chrome browser , as well as Safari( Desktop and iOS).

 This browser supports data from Caniuse, It has more detailed data , The number indicates that the browser supports this version and above .

But don't be reluctant to use this on your website API. It's easy to implement a back-up feature for browsers that don't support it , You'll see .

Some of the requirements for using it

In your own Web This is used in the project API Before , Two things to note :

  • Your website must go through HTTPS Provide services . To promote local development , When your site passes through localhost Runtime , The API You can also use .
  • To prevent abuse ,API Only in response to some user actions ( Like the click event ) Trigger when .

This is an example

To demonstrate how to use this API, I've got one demo, It works on the same principle as on my website . This example uses DIY The way , Customize your own sharing dialog .

here , Once you click the share button , A dialog box will pop up , Show several options for sharing content , This is part of the code , Can help us achieve this goal :

shareButton.addEventListener('click', event => {
  shareDialog.classList.add('is-open');
});

Let's continue with the example transformation , In order to use Web Share API. The first thing to do is to check whether the user's browser really supports the API, As shown below :

if (navigator.share) {
  // Web Share API is supported
} else {
  // Fallback
}

Use Web Share API It's like calling navigator.share() Method and pass an object containing at least one of the following fields .

  • url: A string , Represents what you want to share URL. It's usually the URL of the document , But it's not necessary . You can Web Share API Share anything URL.
  • title: String representing the title to be shared , Usually document.title.
  • text: Any text you want to include .

The actual situation is as follows :

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 {
    // fallback
  }
});

At this time , Once you click the share button in a supported browser , The native picker will pop up all possible targets that users can share data with . The goal could be social media applications 、 E-mail 、 im 、 SMS or other sign up to share .

API Is based on Promise Of , So you can attach a .then() Method , To display the success message when sharing success , And use .catch() Handling errors .. In practice , You may want to use the following code snippet to get the title of the page and URL:

const title = document.title;
const url = document.querySelector('link[rel=canonical]') ? document.querySelector('link[rel=canonical]').href : document.location.href;

about URL, Let's first check that the page has a canonical URL, If there is , Just use it . otherwise , We from document.location To grab href.

It's a good idea to provide a backup plan

No support for Web Share API In the browser of , We need to provide a backup mechanism , So that users on those browsers can still use some sharing options .

Above DIY In the example , We pop up a dialog box , There are some options for sharing content , And the buttons in the demo don't actually link anywhere , Because it's a demonstration . however , If you want to know how to create your own links to share web pages without using third-party scripts , that Adam Coti The article It's a good starting point .

What we have to do is not support Web Share API A backup dialog box will be displayed for the user on the browser . It's like moving the code that opens the shared dialog box to else It's as simple as in the block :

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');
  }
});

Now? , Whatever browser you use , All users will be covered . Here's how the share button works on both mobile browsers , One is to support Web Share API, The other is not supporting .

Try it ! Use support Web Share Browser and unsupported browser . It should work like the demo above .

end

About what you need to know about Web Share API Basic content . By implementing it on your website , Visitors can more easily share your content with contacts and other native applications on a wider social network .

Another thing to note , If your Web The application conforms to WPA Web Apply installation standards , You can add it as a shared target , And add it to the user's home screen .Web Share Target API This function of , You can go to Google Developers Learn more about .

Although there is not much support for browsers , But it's easy to go back , So I don't think there's any reason not to adopt this approach .

Have you ever used Web Share API? Please share... In the comments .


original text :https://css-tricks.com/how-to...

版权声明
本文为[Dunib]所创,转载请带上原文链接,感谢