Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
// Created by STRd6
// MIT License
// jquery.paste_image_reader.js
(function($) {
var defaults;
$.event.fix = (function(originalFix) {
return function(event) {
event = originalFix.apply(this, arguments);
if (event.type.indexOf('copy') === 0 || event.type.indexOf('paste') === 0) {
event.clipboardData = event.originalEvent.clipboardData;
}
return event;
};
})($.event.fix);
defaults = {
callback: $.noop,
matchType: /image.*/
};
return $.fn.pasteImageReader = function(options) {
if (typeof options === "function") {
options = {
callback: options
};
}
options = $.extend({}, defaults, options);
return this.each(function() {
var $this, element;
element = this;
$this = $(this);
return $this.bind('paste', function(event) {
var clipboardData, found;
found = false;
clipboardData = event.clipboardData;
return Array.prototype.forEach.call(clipboardData.types, function(type, i) {
var file, reader;
if (found) {
return;
}
if (type.match(options.matchType) || clipboardData.items[i].type.match(options.matchType)) {
file = clipboardData.items[i].getAsFile();
reader = new FileReader();
reader.onload = function(evt) {
return options.callback.call(element, {
dataURL: evt.target.result,
event: evt,
file: file,
name: file.name
});
};
reader.readAsDataURL(file);
return found = true;
}
});
});
});
};
})(jQuery);

MeTe-30 commented Sep 18, 2014

Hi,
Your code is working very well, thanks.
Just one question!
I want to paste an image by pressing ctrl+v or hitting button, but i don't know how to trigger your paste event after hitting the button.
I tried everything but none of them worked.
plz HELP!!

Owner

STRd6 commented Sep 21, 2014

You can't trigger a paste event for the user other than through direct user interaction (ctrl+v, context menu 'paste', or dropping content). It's a web security issue. There may be a way for your page to request additional clipboard permissions to allow for script generated clipboard events, but I'm not sure of the details.

how to use image copy and paste at web editor

can anybody guide me ?

Hi,

I am using html editor of extjs and want to paste image in text editor.
Can you please guide me that how can we integrate this code with extjs html editor.
Thanks is advance for your help.

example of usage

https://codepen.io/netsi1964/pen/IoJbg

thanks for the code !

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