Copy Text and Image using clipboard in JS

170 Views Asked by At

I am trying to copy an image with a text and paste to slack. It works when i try to copy it to notepad but wont work when i copy the same to slack.

JS code :

const btn = document.getElementById("btn");
const out = document.getElementById("out");


btn.addEventListener("click", async () => {
  try {
    const html = `
      <img src="https://picsum.photos/seed/picsum/200/300">
      <p>Random string</p>
    `;
    
    const data = [
      new ClipboardItem({
        "text/html": new Blob([html], {
          type: "text/html"
        })
      })
    ];

    navigator.clipboard.write(data).then(
      () => {
        out.innerText = "Copied to clipboard!";
      },
      (err) => {
        out.innerText = "Error: " + err;
      }
    );
  } catch (err) {
    out.innerText = "Error: " + err;
  }
});

HTML :

<p>Click Copy, then paste into Word/Teams/Slack</p>


<button id="btn" type="button">Copy HTML (works)</button>

<pre id="out"></pre>
1

There are 1 best solutions below

0
Alexander Polyankin On

This is because you need use image-based MIME types in ClipboardItem. There is a modified example from MDN:

btn.addEventListener("click", async () => {
  try {
    const imgURL = "https://picsum.photos/seed/picsum/200/300";
    const data = await fetch(imgURL);
    const blob = await data.blob();

    await navigator.clipboard.write([
      new ClipboardItem({
        [blob.type]: blob,
      }),
    ]);
  } catch (err) {
    console.error(err.name, err.message);
  }
});