Drag and Drop: How to get the URL of image being dropped if image is a link (not the url of the link)

Using jQuery. (I'm just using it to get the "src" attribute so i think you can do without it)

I replaced:

var imageUrl = evt.dataTransfer.getData('URL');

with:

var imageUrl = evt.dataTransfer.getData('text/html');

Oh, and I replace the alert with a console.log so you'll need to open it.


Here's how I'd do it (only tested in Firefox):

  • use jQuery
  • analyze the dropped html-code using jQuery: search for image inside with .find()
  • read src-attribute from the found image with .attr()

Here's the important part from my new drop(event) function:

// Get text/html instead of text/uri-list!
// So you get raw html that is passed even between different websites
var droppedHTML = evt.dataTransfer.getData("text/html");

// add this html to some container.
// if you skip this, the following code won't work if a single img element is dropped
var dropContext = $('<div>').append(droppedHTML);

// now you can read the img-url (not link-url!!) like this:
var imgURL = $(dropContext).find("img").attr('src');

function drop(evt) {
    evt.stopPropagation();
    evt.preventDefault(); 
    var imageUrl = evt.dataTransfer.getData('text/html');
    var rex = /src="?([^"\s]+)"?\s*/;
    var url, res;
    url = rex.exec(imageUrl);
    alert(url[1]);
}

It works on Chrome and Firefox, but note that if you drag an image from Chrome to Firefox it doesn't work.