Search code examples
javascripthtmlfilereaderclipboarddata

HTML5 and JavaScript: How do I make paste handling fully/more asynchronous?


I'm implementing copy-paste functionality into a browser application using the ClipboardData API, as explained in this answer.

The FileReader::readAsDataURL(blob) provides asynchronous reading of the file data, which is great.

var items = (event.clipboardData || event.originalEvent.clipboardData).items;
var reader = new FileReader();
reader.onload = function(event){
   /*add item (i.e. image) to page*/}; //callback

var blob = items[0].getAsFile(); //not async
reader.readAsDataURL(blob); //async

Questions:
1) Is there a way to make the DataTransferItem::getAsFile() method asynchronous?
2) Is there a way to get FileReader to take a DataTransferItem as an argument so it can do the async itself like it does already with blobs?
3) Am I out of luck?


Solution

  • Is there a way to make the DataTransferItem::getAsFile() method asynchronous?

    No. It's specified as synchronous. However, there is absolutely no reason to make this asynchronous - a reference to the File is quickly constructed and does not incorporate any data shoveling. Just as input.files does synchronously get you references to not-yet-read-in files.

    Is there a way to get FileReader to take a DataTransferItem as an argument so it can do the async itself like it does already with blobs?

    No. It just takes the item.getAsFile() blob, and can read that in asynchronously.