Skip to content

Instantly share code, notes, and snippets.

@dusanmarsa
Created October 29, 2017 08:43
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save dusanmarsa/2ca9f1df36e14864328a2bb0b353332e to your computer and use it in GitHub Desktop.
Save dusanmarsa/2ca9f1df36e14864328a2bb0b353332e to your computer and use it in GitHub Desktop.
JavaScript - Clipboard API - Paste image handler
var IMAGE_MIME_REGEX = /^image\/(p?jpeg|gif|png)$/i;
var loadImage = function (file) {
var reader = new FileReader();
reader.onload = function(e){
var img = document.createElement('img');
img.src = e.target.result;
var range = window.getSelection().getRangeAt(0);
range.deleteContents();
range.insertNode(img);
};
reader.readAsDataURL(file);
};
document.onpaste = function(e){
var items = e.clipboardData.items;
for (var i = 0; i < items.length; i++) {
if (IMAGE_MIME_REGEX.test(items[i].type)) {
loadImage(items[i].getAsFile());
return;
}
}
e.PreventDefault()
}
@martindrapeau
Copy link

Great little gist. I turned this into a mini web-app to demonstrate pasting an image in a web page.
https://martindrapeau.github.io/image-clipboard/

@dusanmarsa
Copy link
Author

Great little gist. I turned this into a mini web-app to demonstrate pasting an image in a web page.
https://martindrapeau.github.io/image-clipboard/

Oh, Github didn't give me any notice about your comment but late answer better than no answer at all, right? 🙂 Glad to help. Nice app you got there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment