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:
Resources: Specification for HTML5 drag and drop.
Now HTML 5 came up with a Drag and Drop (DnD) API that brings native DnD support to the browser making it much easier to code up. HTML 5 DnD is supported by all the major browsers like Chrome, Firefox 3.5 and Safari 4 etc.
The ondragover event specifies where the dragged data can be dropped. By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element.
setData() The DataTransfer. setData() method sets the drag operation's drag data to the specified data and type. If data for the given type does not exist, it is added at the end of the drag data store, such that the last item in the types list will be the new type.
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.
Referencing this answer:
The data is only available on drop, this is a security feature since a website could grab data when you happen to be dragging something across the webpage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With