3

how to share image with source from <img src="example.jpg"> use web share api. This my code not work

let file = "https://tukarjual.com/images/ads/all-category.jpg"
        let filesArray = [file]

        if (navigator.canShare && navigator.canShare({ files: filesArray })) {
            await navigator.share({
                files   : filesArray,
                title   : 'Layanan TukarJual',
                text    : 'Ayo dukung karya putra daerah Kotabaru dengan belanja online di TukarJual',
                url     : 'https://tukarjual.com'
            })
        }
Hendri Arifin
  • 31
  • 1
  • 4

1 Answers1

4

You need to share the image as a blob. Therefore, first convert the image to a blob and then share it. An easy way to do this is by calling fetch():

const blob = await fetch('https://cdn.glitch.com/f96f78ec-d35d-447b-acf4-86f2b3658491%2Fchuck.png?v=1618311092497').then(r=>r.blob())

You can then pass this blob to your share function:

const share = async (title, text, blob) => {
  const data = {
    files: [
      new File([blob], 'file.png', {
        type: blob.type,
      }),
    ],
    title: title,
    text: text,
  };
  try {
    if (!(navigator.canShare(data))) {
      throw new Error("Can't share data.", data);
    }
    await navigator.share(data);
  } catch (err) {
    console.error(err.name, err.message);
  }
};
Dharman
  • 30,962
  • 25
  • 85
  • 135
DenverCoder9
  • 2,024
  • 11
  • 32
  • What if the image is from a different source and the browser thinks it's an enormous security risk to allow a user to share an image that happens to be from a different server than the page they're on? – Nic Estrada Jan 24 '23 at 23:15
  • In theory this could happen, for example, if the image URL is from a domain that the Safe Browsing feature has determined as insecure. – DenverCoder9 Jan 31 '23 at 10:41