Not able to share an image with text using Navigator.share

57 Views Asked by At

I want to share an image with a caption. Here I have the code which generates an image dynamically using the html-to-image plugin.

However, when I share the image (WhatsApp, Facebook) the text is discarded.

On the other hand, if I pass two files as an image and try to share them, the text is included in both images.

getScoreImage() {
    this.dynamicImageEle = document.getElementById('quiz-share-image-wrap');

    const v_this = this;

        htmlToImage.toPng(this.dynamicImageEle)
        .then(function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
        v_this.dynamicImageBase64 = img.src;
        const file = v_this.dataURLtoFile(dataUrl, "ipl-quiz.png");

        setTimeout(()=> {
            v_this.shareFile(file);
        },100)
    })
    .catch(function (error) {
        console.error('oops, something went wrong!', error);
    });
}

dataURLtoFile(dataurl: any, filename:any) {
    var arr = dataurl.split(","),
        mimeType = arr[0].match(/:(.*?);/)[1],
        decodedData = atob(arr[1]),
        lengthOfDecodedData = decodedData.length,
        u8array = new Uint8Array(lengthOfDecodedData);
    while (lengthOfDecodedData--) {
        u8array[lengthOfDecodedData] = decodedData.charCodeAt(lengthOfDecodedData);
    }
    return new File([u8array], filename, { type: mimeType });
    
};

async shareFile(file:any) {
    if (navigator.canShare && navigator.canShare({ files: [file] })) {
        await navigator.share({
            "title": this.shareTitle,
            "text": this.shareText,
            "files": [file, file],
        })
        .then(() => console.log("Share was successful."))
        .catch((error) => console.log("Sharing failed", error));
    } else {
        console.log(`Your system doesn't support sharing files.`);
    }
};

Current output with image and no text

If I pass two images then output is proper but 2 image is not expected

The expected output is image with text

1

There are 1 best solutions below

0
Mustafa Jamal On

this API has some inconsistency while working with it. and I'm currently facing this same issue; for now, I might get over it by building a dynamic image (with text overlapped) and then sharing it.

or I would make the image available via a link (image preview) and share text with it.

sorry that I couldn't add this answer in the comment section as I don't have enough reputation.