简体   繁体   中英

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

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() (ie, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM