Share Image With Web Share API

Kush Kumar
3 min readMay 22, 2021

--

With growing web apps and ease of use, sometimes the user needs to share the content over social media from the web app. Sharing text or URLs from a web app to social media is quite easy, but sharing the files from a web app to social media is quite tricky, to make it happen Web Share API can be used.

Web Share API demo

Native intent with Web Share API

Working with one of my recent projects I thought to share a dynamic banner with a user name where the user can share the banner over social media to show his/her contribution.

Initially, I tried to store the user banner to firebase and sharing the file URL to social media but sharing the file as the image would be more relevant than sharing an image URL. Then found the Web Share API which uses the user device to share the file, text, URL to social media. On the action of the user, the intent will open which will have all apps which support sharing option, out of which the user can choose to share.

left android intent right IOS intent

Step 1

Used html-to-image package to create the image

With the use of the html-to-image package, I was able to take a portion of div with its elementId and convert that portion to base64. Package support promise so we can catch the error if it’s encountered.

html to image import statement

Step 2

dataUrlToFile is a helper function that takes base64 and the file name as parameters. It returns the temporary file location.

This helper function is used in step 4

Creating file from base64

Step 3

shareFile is another helper function that is created to share the file along with title and text.

navigator.canShare : checks the browser support

navigator.canShare({files: [file]}) : checks whether shared file is supported or not

navigator.share : triggers the intent that shows all the apps that support share option

This helper function is used in step 4

navigator.canShare({files: [file]}) checks weathe

helper function to sharing file

Step 4

With the elementId thanku_poster I am creating a base64 data with package html-to-images function toJpeg.

Once base64 is created with the dataUrlToFile helper function creating the file location.

Once the creation of file location is done shareFile helper function is called to share the content.

Creating base64 of image and sharing code

Web Share API — Features and Limitations

Features

  • Web apps can use the system-provided sharing capabilities just like a platform-specific app.
  • Developers get a more comprehensive range of sharing options.
  • Web Share APIs help to share files, text, and URLs.

Limitations

  • It can only be used on a site that is accessed via HTTPS.
  • It can share, URLs, text, or files.
  • The intent will open on user actions on page load it can’t open
Supported browser

References

--

--

Responses (1)