'paste image in Whatsapp chat using js in chrome extension
I want to paste image from my clipboard to whatsapp chat from clipboard i tried using document exec command with different parameters like insertHTML , insertImage these two add image in content editable div but does not enable the send button. I also tried using document exec command paste but its pasting nothing. I double checked and images exists on clipboard.
async function sendToChat(blob) {
setToClipboardImg(blob)
try {
document.querySelector('._6h3Ps ._13NKt').focus()
} catch (e) {
document.querySelector('textarea').focus()
}
// const data = [new ClipboardItem({
// [text.type]: text
// })]
// await navigator.clipboard.write(data)
document.execCommand("Paste", null, null);
//setToClipboardWithTextInsta()
}
var setToClipboardImg = async blob => {
window.focus();
const data = [new ClipboardItem({
[blob.type]: blob
})]
await navigator.clipboard.write(data);
}
Solution 1:[1]
I needed exactly the same funcionality, I was able to resolve it using html2canvas, you can convert an html element into an image and then send it through whatsapp from the clipboard, here is how I implemented it:
document.querySelector("#btn").onclick(function () {
var table = document.querySelector("#table");
var elementContainer = document.querySelector("#previewImage");
try {
// Prevent duplicates since the element will be appended to the container
if (elementContainer.innerHTML) {
elementContainer.innerHTML = "";
}
html2canvas(table).then(canvas => {
elementContainer.appendChild(canvas);
canvas.toBlob(blob => navigator.clipboard.write([new
ClipboardItem({'image/png': blob})]));
alert('? The screenshot for the table currently displayed was copied to the clipboard, you can now paste into the WhatsApp chats ?');
});
}
catch(err){
document.querySelector("#output").innerHTML = err.message;
}
}
Then in the head of the document add the following cdn:
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |