Drag & Drop - DataTransfer Object

I create a simple drag n 'bootloader, and I wonder why I don’t see the files that I drop when I console.log(e) (DragEvent) and look at DragEvent.dataTransfer.files , it appears empty, but. .. if I console.log(e.dataTransfer.files) , it will show the dropped file (s).

// CODE

 <!DOCTYPE html> <html> <head> <script> document.addEventListener("DOMContentLoaded", init); function init(){ var dropbox = document.getElementById('dropbox'); dropbox.addEventListener('dragover', drag.over); dropbox.addEventListener('drop', drag.drop); } var drag = { "over": function(e){ e.preventDefault(); }, "drop": function(e){ e.preventDefault(); console.log(e); //NO FILES SHOWN console.log(e.dataTransfer.files); //FILES in FileList Object } }; </script> <style> body{ margin: 0 !important; height: 100vh; width: 100vw; display: flex; justify-content: center; } #dropbox{ height: 400px; width: 400px; align-self: center; background-color: #0089C4; border-radius: .3em; border: 1px dashed black; -webkit-box-shadow: 0px 2px 7px rgba(0, 0, 0, 0.40); box-shadow: 0px 2px 7px rgba(0, 0, 0, 0.40); } </style> </head> <body> <div id="dropbox"></div> </body> </html> 
+8
javascript html5 drag-and-drop drag
source share
1 answer

The drag datastore has different modes depending on when you access it:

  • Enable dragstart event in read / write mode.
  • In the drop event, it is in read - only mode.
  • And in all other events it is in protected mode.

    Protected mode is defined as follows:

Protected mode

For all other events. Formats and views in the drag and drop data store You can list the items that represent the data to be dragged, but the data itself is not available and new data cannot be added.

See here: https://html.spec.whatwg.org/multipage/interaction.html#the-drag-data-store

This means that when accessing the dataTransfer object in the console, which is not in the drop or dragstart , it is in protected mode, which prevents access to data.

You can view fileList because you are logging a fileList on drop event when dataTransfer is being read. But if you register e.dataTransfer or e , you will not be able to access any data.

Here you can check, even on dragover you cannot access dataTransfer :

 document.querySelector('#droppable').ondragover = function(e) { console.log('on dragover files are', e.dataTransfer.files) e.preventDefault(); } document.querySelector('#droppable').ondrop = function(e) { console.log('on drop files are', e.dataTransfer.files) e.preventDefault(); } 
 <div id=droppable>Drop a file</div> 
+6
source share

All Articles