Quantcast
Channel: Updates
Viewing all articles
Browse latest Browse all 599

Share files with Web Share

$
0
0

Share files with Web Share

System-level share target picker with installed PWA as an option.

Over the last few years, we've been working to bring native sharing capabilities to the web. The Web Share API allows web apps to invoke the same share dialog box that a native app user would see. The Web Share Target API allows web apps to receive data from a share.

The only resource previously supported by these APIs was links. Chrome 75 adds support for Web Web Share API - Level 2, making it easy for web apps to share files to other apps using the system provided picker.In the future, you'll also be able to use web apps as a share target. For now, your web app can share files with other web share targets registered on your device.

This article assumes some familiarity with the web share APIs. If this is new to you, check out the links above or the demo.

The canShare() method

If you're familiar with the earlier API, you're used to doing feature detection by testing for navigator.share(). With files it's more complicated. You need to know whether the file a user is sharing is sharable on the current system. To find out, you test for the presence of canShare(), then pass it a reference to the files you want to share.

const shareData = { files: filesArray };
if (navigator.canShare && navigator.canShare(shareData)) {
  // Share the data.
} else {
  console.log('Your system doesn't support sharing files.');
}

Take note of what's not in shareData. When calling canShare() for files, shareData cannot contain other members. If you need title, text, or url you'll need to add them afterwards.

Image, video, audio and text files can be shared (see permitted extensions). More file types may be permitted in the future.

You're now ready to share:

if (navigator.canShare && navigator.canShare( { files: filesArray } )) {
  navigator.share({
    files: files,
    title: 'Vacation Pictures',
    text: 'Barb\nHere are the pictures from our vacation.\n\nJoe',  })
  .then(() => console.log('Share was successful.'))
  .catch((error) => console.log('Sharing failed', error));
} else {
  console.log('Your system doesn't support sharing files.');
}

It may seem odd to include other data members when sharing files. Allowing these members explands the flexibility of use cases. Imagine if after running the code above, the user chose an email application as the target. The title parameter might become an email subject, the text, the body of the message, and the files, attachments.

Note: The shareData argument is required for both canShare() and share() even though the specification labels it as optional in both cases. As the specification itself states, this is because of a quirk of the Web IDL rules.

More information

Feedback


Viewing all articles
Browse latest Browse all 599

Trending Articles