javascript 如何使用 Chrome 用户脚本获取已放置图像的 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22872651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:55:45  来源:igfitidea点击:

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

javascriptgoogle-chrome-extensiondrag-and-dropdom-events

提问by Ben Taitelbaum

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 debuggerline, I'm getting the empty string for e.dataTransfer.getData("text")and e.dataTransfer.getData("url")

在以下 chrome 用户脚本中,如何获取从桌面拖动的图像的 url?在我有debugger线路的地方,我得到了空字符串e.dataTransfer.getData("text")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);

回答by Leiko

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

这是一个 jsFiddle 如何做到这一点:jsFiddle demo