HTML5 Drag and Drop getData() only works on drop event in Chrome?

Chris Pearce picture Chris Pearce · Mar 2, 2012 · Viewed 15.1k times · Source

I'm currently working on a project at work using the HTML5 Drag and Drop API to provide added functionality including dragging items in and out of browsers. I am currently coming across issues which are specific to Chrome (otherwise only tested in Firefox, which works as expected).

The issue is that I cannot use the event.dataTransfer.getData(type) method to return the data set on the dragstart event in any events except the drop event.

I set the event like so, after binding to the dragstart event (which DOES fire):

event.dataTransfer.setData('text/plain', "some string")

Then in the drop event, I can get the data fine.

event.dataTransfer.getData('text/plain')

However I cannot use the same method as above on any other events (such as dragover). Even if I try and use the above method on the line after calling setData() (i.e., in the dragstart callback), then it will still return undefined.

So, in Chrome, the issue is that getData in Chrome will always return undefined, except within the drop event callback. (In Firefox, I can successfully get the correct data.)

If you have the reference to the dataTransfer object of the same dragging element, then why should you not be able to get the data until it is dropped?

Just wondering:

  • Has anyone had this trouble with Chrome before?
  • What workarounds are there?
  • Or, is it something Chrome needs to fix?

Resources: Specification for HTML5 drag and drop.

Answer

robertc picture robertc · Mar 2, 2012

WebKit, and hence Chrome, is quite restrictive on when you can call getData. You're not allowed to do it inside dragstart or dragover. I think this is the canonical bug.