Hendri Arifin
Hendri Arifin

Reputation: 61

web share api - share image from url or source

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'
            })
        }

Upvotes: 6

Views: 9645

Answers (1)

DenverCoder9
DenverCoder9

Reputation: 2587

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);
  }
};

Upvotes: 6

Related Questions