Enable OS supported share dialog on your website for mobile devices (Part 2)

Enable OS supported share dialog on your website for mobile devices (Part 2)

A couple of days ago I wrote the part 1 of this post which outline everything involved in setting up the share dialog which is common to native apps on your mobile apps.

In this post, we will be looking at how to add support for sharing media files from your web app into apps installed on your users.

The code

Firstly, we will test for the availability of the share feature but a little bit different from what we did when we were sharing text in the part 1 of this post:

   if (navigator.canShare && navigator.canShare({ files: codePictures })) {
        //code here
   }

The canShare property is a helper method that helps to test for the availability of the share feature on the browser. See list of supported browsers here.

Now, we have replaced the url with the files option. The files option can accept an array or a single file. You may have saved these from a form or a URL on your website and simple store it in the codePictures array:

const shareInfo = {
   title : 'My new year resolution',
   text : 'Join the #100DaysOfCode Challenge',
   files: codePictures,
}

if(navigator.share){
  btn.addEventListener('click', () => {
    navigator.share(shareInfo)
    .then( () => console.log('Images shared successfully'))
    .catch( (error) => console.log('An error occured ', error))
  })
}

And that's it! You've just imitated the share behaviour of native apps on your website!

I'd love your feedback on this article. Did you try it out? Did it work for you? What problems did you have?, etc.

Remember to like, share and comment ✌