Web Share API sharing files Permission Denied

1.5k Views Asked by At

I'm not sure what I'm doing wrong here, I think there should be more documentation or better error descriptions for this Web Share API.

I'm trying to share the following file

{
  lastModified: 1622843015507
  lastModifiedDate: Fri Jun 04 2021 16:43:35 GMT-0500 (Eastern Standard Time) {}
  name: "60b1d17b7f2cd71c8307fae2"
  size: 37835
  type: "image/png"
  webkitRelativePath: ""
}

using

await navigator.share({
    text: 'TEST',
    files: [file],
  });

I've made sure that the type is a permitted type, but I keep getting DOMException: Permission denied. I really don’t understand what should I be looking for.

3

There are 3 best solutions below

0
On

I see you have gotten some feedback on the issue that you raised already. Here is a concrete example that hopefully helps you get started:

if (navigator.canShare && navigator.canShare({ files: filesArray })) {
  navigator.share({
    files: filesArray,
    title: 'Vacation Pictures',
    text: 'Photos from September 27 to October 14.',
  })
  .then(() => console.log('Share was successful.'))
  .catch((error) => console.log('Sharing failed', error));
} else {
  console.log(`Your system doesn't support sharing files.`);
}

One way of getting a files array (the filesArray above) is through an <input type=files> element. See the official example for this.

0
On

I think the issue you're facing is the fact that your file name doesn't have an extension. Try adding .png to the file name, it should automagically work.

const file = new File(['hello'], 'hello.png', { type: 'image/png' });
await navigator.share({ files: [file] });
0
On

I had the same issue with a pdf file I had stored as a Blob. Kept getting the 'Permission Denied' error:

 if (pdfBlob && pdfBlob.type && pdfBlob.type.startsWith('application/pdf')) {
        const fileName = report.id.toString(); 
        const file = new File([pdfBlob], fileName);        
        const files = [file];       
        if (navigator.canShare({files})) {                
            navigator.share({
                files: files,
            })
                .then(() => console.log('PDF shared successfully'))
                .catch(error => console.error('PDF sharing failed:', error));
        } else {
            console.log('PDF sharing is not supported in this browser.');
        }
    }
    else {
        console.error('Invalid Blob: Not a PDF file.');
    }

I was missing two things:

  1. Adding the extension to the file name, like @François Beaufort said: "Try adding .png to the file name, it should automagically work."
  2. Including the proper file type as the third parameter, in my case: {type: 'application/pdf'}.

The end result:

const file = new File([pdfBlob],  report.id.toString() + '.pdf', {type: 'application/pdf'});

This worked perfectly!