How do I get the URL for a dropped image using a Chrome userscript?

我怕爱的太早我们不能终老 提交于 2020-01-24 02:19:08

问题


In the following chrome user script, how can I get a url for an image that I drag from my desktop? Where I have the debugger line, I'm getting the empty string for e.dataTransfer.getData("text") and e.dataTransfer.getData("url")

// ==UserScript==
// @match http://*/*
// @match https://*/*
// ==/UserScript==

function preventDrag(e) {
  e.stopPropagation();
  e.preventDefault();
}

function handleDrop(e) {
  console.log("Just dropped: " + e.dataTransfer.files[0].name);
  debugger
  // TODO: grab the url for e.dataTransfer.files[0]

  e.stopPropagation();
  e.preventDefault();
}

document.addEventListener('drop', handleDrop, false);
document.addEventListener('dragenter', preventDrag, false);
document.addEventListener('dragover', preventDrag, false);

回答1:


Not sure I understand it well, but if I do, you won't be able to have a file path (meaning the dropped file fullpath).
It's a "protection" from browsers. But you can at least get the name of it.

var file   = e.originalEvent.dataTransfer.files[0],
    reader = new FileReader();

reader.onloadend = function (event) {
    console.log(file);
    // filename is in file.name
    // ... do something here
}

reader.readAsArrayBuffer(file);

Here is a jsFiddle of how to do it: jsFiddle demo



来源:https://stackoverflow.com/questions/22872651/how-do-i-get-the-url-for-a-dropped-image-using-a-chrome-userscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!