javascripthtmlshare

How to generate and share a file?


I want to share a csv file through the api web share, but instead of using an uploaded file as in the tutorial demos, I want to use a generated file, similar to what is done in this question.

What I'm doing is

navigator.share({
    files: [new Blob([data], {type: type})],
    title: 'Vacation Pictures',
    text: 'Photos from September 27 to October 14.',
  })
  .then(() => console.log('Share was successful.'))
  .catch((error) => console.log('Sharing failed', error));

Solution

  • It needs to be a File object, not just a Blob:

    const file = new File(["foo bar"], "foobar.txt", { type: "text/plain" });
    
    if (navigator.canShare && navigator.canShare({ files: [ file ] })) {
      navigator.share({
        files: [file],
        title: 'Dummy text file',
        text: 'Some dummy text file',
      })
      .then(() => console.log('Share was successful.'))
      .catch((error) => console.log('Sharing failed', error.message));
    }
    else {
      console.log("can't share this");
    }
    

    But note that this file member is only in the level-2 specs, which is still just a draft (accessible under chrome://flags/#enable-experimental-web-platform-features in Chrome).