1

I need to store one image and text in clipboard. I'd like to use Clipboard API. Is it possible?

I'm using following sample to store Image or Text but is it possible to combine?

    copyImgBtn.addEventListener('click', async () => {
    const response = await fetch(img.src)
    const blob = await response.blob()
    const blob1 = new Blob([textarea.value], { type: 'text/plain' })

    var data = [new ClipboardItem({[blob.type] : blob})]
    navigator.clipboard.write(data).then(function() {
      console.log("Copied to clipboard successfully!");
    }, function() {
      console.error("Unable to write to clipboard. :-(");
    })
  }
)

Thank you

1 Answers1

0

As you cannot write multiple ClipBoardItems at once, I used a single text/html blob. (Note that the below snippet will not run here, because of browser permissions policy)

I found the blobToBase64 function here: https://stackoverflow.com/a/18650249/91017

Hope this helps,

Koen

async function copyToClipboard() {
  const imageUrl = 'https://i.picsum.photos/id/739/200/300.jpg?hmac=xApsFbHx511SUVG612QiltrATotVTYu3Q4wfvGyYC1g';
  try {
    const imageData = await fetch(imageUrl);
    const imageBlob = await imageData.blob();
    const imageBase64Data = await blobToBase64(imageBlob);
    const html =
      `<p>Some text</p>
      <p><img src="${imageBase64Data}" alt="Some image"></p>`;

    const textBlob = new Blob([html], {
      type: 'text/html'
    });
    await navigator.clipboard.write([
      new ClipboardItem({
        [textBlob.type]: textBlob
      })
    ]);
    console.log('Copied.');
  } catch (err) {
    console.error(err.name, err.message);
  }
}

function blobToBase64(blob) {
  return new Promise((resolve, _) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsDataURL(blob);
  });
}
<button onclick="copyToClipboard()">Copy text and image to clipboard</button>
Koen Weyn
  • 989
  • 1
  • 7
  • 12