LuisAFK
LuisAFK

Reputation: 957

navigator.share() not working in HTTPS and in a supported browser

I don't understand why navigator.share() is giving me an error even though my website meets all of the requirements listed on MDN (has HTTPS and supported by the browser).

The following code gives an error when I click the button:

Uncaught (in promise) DOMException: Permission denied

shareScoreBtn.addEventListener('click', e => {
  if (!(navigator.canShare && navigator.share))
  {
    console.log('This browser does not support sharing');
    showPopup('Error', 'This browser doesn\'t support sharing');
    return;
  }

  const toShare = {
    text: 'Check out my score in Perfectly Balanced!',
    url: 'https://pb.luisafk.repl.co',
    files: [
      new File([
        deathScreenshots[0]
      ], 'perfectly-balanced-score.png')
    ]
  };

  if (navigator.canShare(toShare))
  {
    navigator.share(toShare).then(() => {
      console.log('Shared death screenshots');
    }).catch(err => {
      console.error('Error sharing death screenshots:', err);
    });
  }
  else
  {
    delete toShare.files;
    toShare.text = `I got a score of ${score} in Perfectly Balanced!`;

    if (navigator.canShare(toShare))
    {
      navigator.share(toShare).then(() => {
        console.log('Shared score text');
      }).catch(err => {
        console.error('Error sharing score text:', err);
      });
    }
    else
    {
      showPopup('Error', 'Your browser doesn\'t support sharing');
      console.log('This browser does not support sharing the deathScreenshots or text');
    }
  }
});

What am I doing wrong?

The website is served over HTTPS and my browser supports the Web Share API according to Mozilla and I also checked in the console !!(navigator.canShare && navigator.share)

Doesn't work on Windows 10 or Chrome on Android.

EDIT: it says (in promise) but the only promise made in that code is by navigator.share() which according to MDN can't reject with a DOMException so I don't really know what's happening. If I use canShare and share in the console it works fine...

EDIT: Many people misunderstood the question, so I will clarify it. My question is what is causing navigator.share() to error?

Upvotes: 3

Views: 6077

Answers (2)

LuisAFK
LuisAFK

Reputation: 957

I found the answer here

You must specify the MIME type of the blobs to the new File constructor as follows:

new File([ blob ], 'filename.png', { type: blob.type })

Upvotes: 2

Michal Měchura
Michal Měchura

Reputation: 211

I think that every time you're calling navigator.share() you need to call it with the await operator, like this:

await navigator.share();

Otherwise any exceptions raised inside the promise returned by navigator.share() will not be caught by your try/catch block.

Upvotes: 0

Related Questions