How to fix Web Share API firing twice under Android Chrome
Nil Portugués Calderó

Nil Portugués Calderó @nilportugues

About: Meta programmer. CS Engineer. Tech Lead. Software Engineer doing Java, JS, Python, PHP. Learning Big Data & ML

Location:
Barcelona
Joined:
May 4, 2017

How to fix Web Share API firing twice under Android Chrome

Publish Date: Sep 30 '19
7 0

I wanted to share with everyone around a small hack I had to write when working with the Web Share API.

What is this Web Share API in the first place?

For those knowing little to nothing on the Web Share API, Google Developers has a nice write up about it and a video showing how it works.

Fixing the Bug

We just want to make sure the Web Share API opens just once.

Currently, there's a bug in Chrome and Chromium browsers running in Android devices.

Bug currently will cause Chrome to open the share dialog twice, one stacked one over the other. And this is terrible UX.

I had to come up with a solution or ditch the functionality and fallback to a custom share modal, which I didn't want to if I could go native.

So I came up with a decent hack: A boolean flag. Sound's easy right?

The Solution

In order to keep track of this action before, and after the user interacts with the Web Share API I decided to pollute the navigator global variable and add a new property to it called running.

Code is as follows:

if (navigator.share !== undefined && location.protocol == 'https:') {

    if (navigator.running == true) {        
      return;
    }

    navigator.running = true;
    navigator
      .share({ 
           title: "NilPortugues.com",
           text: "I just want to share this with you", 
           url: "https://nilportugues.com" 
      })
      .then(() => {
        navigator.running = false;
      })
      .catch(error => {
        navigator.running = false;
        console.log(error)
      });

} else {
  alert('Your browser does not support Web Share API yet.');
}
Enter fullscreen mode Exit fullscreen mode

It just works.

Hopefully, this will help someone out there facing the same problem.

Comments 0 total

    Add comment