How can I detect a copy image browser event?

Using jquery, I can detect when the user is copying something (e.g. text) using ctrl-c or via the context menu:

$(document).on('copy',function(e){$('body').prepend('copy event <br>');}); 

However, the event does not seem to fire when the image is copied. How can I detect a copy of an image? In particular, I would like to detect copying from the <canvas> , but any <img> should do as a starting point for understanding this problem.

Test scenario: http://jsfiddle.net/jm23xe8w/

+6
source share
1 answer

Browsers do not have image copy events, so you need to simulate it using some tricks.also the clipboard does not save images in it. Clipboard only saves texts by itself. You need to convert the images to base64 encoding, then save it to the clipboard and paste it into your application. But there is a problem with this: this is clipboard data, copied images, or some other data of some other application in it. To do this, you can add a unique string to your encoded string first and / or at the end, and check it where you want to insert it. To convert images to a base64encode string, you can use this code:

 function getImageData(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); var imgd = canvas.toDataURL("image/png"); return imgd; } 

Pass the img tag to this function to get the result.

0
source

Source: https://habr.com/ru/post/977654/


All Articles