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粉8839734812024-01-29 20:56:31
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粉9165538952024-01-29 13:38:48
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
ssscccHello world!
Inspired by @denvercoder9!