Share images via social media using PWA
P粉300541798
P粉300541798 2024-01-28 22:02:28
0
2
409

In my Nuxt PWA, I have a function that converts HTML to Canvas using this package. The generated image is in base 64. Now I want to be able to share the image via: Whatsapp, Facebook, Email, Instagram, etc. I've found a few packages, but none of them seem to support sharing just file URLs and text.

This is my sharing function:

shareTicket(index) {
  html2canvas(this.$refs['ticket-' + index][0], {
    backgroundColor: '#efefef',
    useCORS: true, // if the contents of screenshots, there are images, there may be a case of cross-domain, add this parameter, the cross-domain file to solve the problem
  }).then((canvas) => {
    let url = canvas.toDataURL('image/png') // finally produced image url

    if (navigator.share) {
      navigator.share({
        title: 'Title to be shared',
        text: 'Text to be shared',
        url: this.url,
      })
    }
  })

When I take out the if (navigator.share) condition, I get an error in my console saying navigator.share is not a function. I read somewhere that it only works with HTTPS, so I uploaded to my staging server and tried it, but still got the same error.

To be clear, I want to be able to share the generated image itself, not the URL.

P粉300541798
P粉300541798

reply all(2)
P粉883973481

I have a variation of the following code in the share() function in my application and it works fine if executed on the client.

const share = async() => {
  if (!('share' in navigator)) {
    return;
  }
  // `element` is the HTML element you want to share.
  // `backgroundColor` is the desired background color.
  const canvas = await html2canvas(element, {
    backgroundColor,
  });
  canvas.toBlob(async (blob) => {
    // Even if you want to share just one file you need to 
    // send them as an array of files.
    const files = [new File([blob], 'image.png', { type: blob.type })];
    const shareData = {
      text: 'Some text',
      title: 'Some title',
      files,
    };
    if (navigator.canShare(shareData)) {
      try {
        await navigator.share(shareData);
      } catch (err) {
        if (err.name !== 'AbortError') {
          console.error(err.name, err.message);      
        }
      }
    } else {
      console.warn('Sharing not supported', shareData);            
    }
  });
};
P粉916553895

Tell me if this URL works for you: https://nuxt-share-social- media.netlify.app
If so, you can find the Github repository here: https://github.com/ Kissu/so-share-image-bounty

The code is



sssccc

Inspired by @denvercoder9!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!