Accept drag & drop of image from another browser window

Although you are able to accept the drag and drop of an image from another website, you are unable to do any processing of it (e.g. converting it to a base64 string using the canvas) (as of 21st August 2014) because of various cross-origin policy issues.

var dt = event.dataTransfer;
var url = dt.getData('url');
if (!url) {
    url = dt.getData('text/plain');
    if (!url) {
        url = dt.getData('text/uri-list');
            if (!url) {
                // We have tried all that we can to get this url but we can't. Abort mission
                 return;
             }
         }
     }

Even Google can't get around this - If you use gmail, you can drag and drop an image from another location in to the email body, but all this does is create an <img/> element with its src set to url (from the code above).

However, I've created a plugin that allows you to fake it cross-origin drag and drop. It requires a PHP backend.

Read the article I wrote on it here https://coderwall.com/p/doco6w/html5-cross-origin-drag-and-drop


Here's my solution to the problem: Dropzone js - Drag n Drop file from same page

Please do keep in mind that ability to drag an image from another domain depends on their CORS setup.


function drop(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    var imageUrl = evt.dataTransfer.getData('URL');  // instead of 'Text'
    alert(imageUrl);
}

Seems to work in Firefox, Safari, and Chrome on Mac. Also works in Firefox, IE, and Chrome in Windows.

Updated fiddle


UPDATE:

It looks like there are differences between Chrome on Windows and MacOS. On Windows dataTransfer.getData('Text'); works but not on MacOS. dataTransfer.getData('URL'); should work on both.


OLD answer:

You could define a drop zone:

<div id="dropbox">DropZone => you could drop any image from any page here</div>

and then handle the dragenter, dragexit, dragover and drop events:

var dropbox = document.getElementById('dropbox');

dropbox.addEventListener('dragenter', noopHandler, false);
dropbox.addEventListener('dragexit', noopHandler, false);
dropbox.addEventListener('dragover', noopHandler, false);
dropbox.addEventListener('drop', drop, false);

function noopHandler(evt) {
    evt.stopPropagation();
    evt.preventDefault();
}
function drop(evt) {
    evt.stopPropagation();
    evt.preventDefault(); 
    var imageUrl = evt.dataTransfer.getData('Text');
    alert(imageUrl);
}

​ It is inside the drop event handler that we are reading the image data from the dataTransfer object as Text. If we dropped an image from some other webpage this text will represent the url of the image.

And here's a live demo.