Is there a way to select and copy an image to clipboard only with javascript commands?

I want to copy the image itself not any text or related src.

I've made a jsfiddle example https://jsfiddle.net/pvuefca7/1/

You can play around and see that copying text works fine but for the image it does not. i think it has something to do with <img> not being a node or something along those lines. i'm asking if there is any way of selecting a specific image and coping it. the document.execCommand('Copy'); command will copy an image if the image is the only element, IE opening an image in a new tab and running the command in the console. but i need a way of coping an image when its not the only element.

Answers:

Answer

You can request image as Blob at click of button; set .value of <textarea> element to data URI of image within FileReader load event following call to .readAsDataURL(); select .value of textarea; prompt user to press CTRL+C; at copy event handler set .value of textarea at event.clipboardData

<div>
  <img id="image" width="100" src="https://placehold.it/100x100?text=?">
  <button onclick="copyElement('image');">Copy image</button>
</div>
<script>
function copyElement(id) {
  var element = document.getElementById(id);
  var text = document.createElement("textarea");

  document.oncopy = function(e) {
    e.clipboardData.setData("text/plain", text.value);
    console.log(e.clipboardData.getData("text/plain"));
  }

  fetch(element.src.replace(/^(http:|https:)/, location.protocol))
    .then(function(response) {
      return response.blob()
    })
    .then(function(blob) {
      var reader = new FileReader();
      reader.onload = function() {
        document.body.appendChild(text);
        text.value = reader.result;
        text.select();
        alert("Press CTRL+C to copy image to clipboard");
      }
      reader.readAsDataURL(blob)
    })
}

</script>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.