Reputation: 198
I'm trying to write a browser extension that allows users to save pictures from page to favorites (like pinterest, you know). By clicking on the extension icon it adds a special field to html and user can drag any image from the page to it. Then the image uploaded to the server (preferably as a file, but simple url from src="..."
may be usable too). See the example below.
Simple input[type=file]
field does not respond to the page elements. I have tried dropzone.js, it works perfectly with local files, but does not work with page images (it responds, but chrome does not pass proper image object in the "drop" event).
Maybe there's some well-known ways to do it? Or existing JavaScript libraries? I don't really want to modify foreign page code, it may annoy users (for example use heavy jQuery UI and make all img tags draggable). Natural drag'n'drop behavior would be ideal.
Upvotes: 3
Views: 477
Reputation: 198
I found the simple and beautiful solution.
Attach onmousedown
event listener to every img
tag on the page, save URL to temporary variable and read it if ondrop
event fired on upload field.
Simplified example:
var imgURL = "";
$("a, img").on("mousedown", function(e) {
var $target = $(e.target);
if ($target.prop("tagName").toLowerCase() == 'img') {
imgURL = $target.attr('src');
}
});
$("#my-drop-area").on("dragenter dragover dragleave", function(e) {
// need for proper ondrop event activation
e.preventDefault();
e.stopPropagation();
}).on("drop", function(e) {
e.preventDefault();
e.stopPropagation();
console.debug("Dropped! URL:", imgURL);
});
Upvotes: 2