4

I'm am working on an interactive content editing system. In the system, you should be able to freely drag and drop content between the website and your desktop. I use the html5 drag and drop API. Dragging files with a persistent url onto desktop works. However, dragging dynamically-generated content (e.g. some string value) is not working for me (in latest chrome, version 62).

I already tried two possibilities I stumbled upon while researching this issue. Both solutions seem outdated:

  • The first one is using a data url to encode the dynamic content:

const span = document.querySelector("#drag");

span.addEventListener("dragstart", evt => {
  const mimeType = 'text/plain';
  const filename = 'example.txt';
  const content = 'someDynamicContent';
  // using data url:
  const url =  `data:text/plain;base64,${btoa(content)}`;

  evt.dataTransfer.setData("DownloadURL", `${mimeType}:${filename}:${url}`);
})
#drag {
  user-select: none;
  user-drag: element;
}
<span id="drag" draggable="true">Drag me onto Desktop</span>

I'm aware of a very similar, yet old, question (Drag File in Data URI format from Browser to Desktop). The provided answer seems to be outdated and does not work in (at least) chrome 62 anymore.

  • The second one uses URL.createObjectURL to create a temporary url to use as a DownloadURL.

const span = document.querySelector("#drag");

span.addEventListener("dragstart", evt => {
  const mimeType = 'text/plain';
  const filename = 'example.txt';
  const content = 'someDynamicContent';
  // using createObjectURL:
  const url = URL.createObjectURL(new Blob([content], {type : 'text/plain'}));

  evt.dataTransfer.setData("DownloadURL", `${mimeType}:${filename}:${url}`);
});
#drag {
  user-select: none;
  user-drag: element;
}
<span id="drag" draggable="true">Drag me onto Desktop</span>

So the question is, how to perform a drag operation, that gives you a file with the provided content (and not just some link to the Blob's url) on your desktop?

(The proposed solution only needs to work in chrome)

Stefan Ramson
  • 531
  • 1
  • 6
  • 18

0 Answers0