javascript - 如何在 webkit 浏览器中访问粘贴的文件? (如谷歌浏览器)

标签 javascript google-chrome paste fileapi

如果能够在 Stack Exchange 上将图像粘贴到此处而不是插手文件对话框,那将会非常方便。类似的功能是(是?)在这里实现,但是only for Webkit browsers .

我正在开发 userscript that does that .有趣的是,我从来没有完成 file (不同于原始图像数据)来自 Webkit 浏览器中的剪贴板,而在 Firefox 中它可以工作。

Firefox 解决方案:

  div.addEventListener('paste', function(event){
    //I'm actually not sure what should event.originalEvent be. I copypasted this
    var items = (event.clipboardData || event.originalEvent.clipboardData);
    console.log("paste", items);
    //Try to get a file and handle it as Blob/File
    var files = items.items || items.files;
    if(files.length>0) {  
      //Being lazy I just pick first file
      var file = files[0];
      //handle the File object
      _this.processFile(file);

      event.preventDefault();
      event.cancelBubble = true;
      return false;
    }
  });

在 Chrome 没有像 Firefox 那样好的文档(我的意思是 MDN)之前,我试图检查发生了什么。我复制了一个文件并将其粘贴到 Google chrome (v39) 中。这是我在控制台的 DataTransfer 对象中得到的:

paste event Google chrome

作为引用,这是 Firefox 中的相同事件:

paste event files firefox

另外两个数组,itemstypes 在 Firefox 实现中不存在。当我复制文本或原始图像数据时,Chrome 将其表示为 DataTransferItem。我发现最好忽略那些:

  //Being lazy I just pick first file
  var file = files[0];
  //GOOGLE CHROME
  if(file.getAsFile) {
    console.log("DataTransferItem:", file);
    //HTML or text will be handled by contenteditable div
    if(file.type!="text/plain" && file.type!="text/html") {
      //handle the File object
      _this.processFile(file.getAsFile());
    }
  }
  else 
    ...

到目前为止,除了 text/plaintext/html 之外,我从未想过得到任何其他东西。对于这些,.getAsFile 返回 null

我发现 google chrome 模型有点令人困惑。它为您提供了有关原始数据(文本/原始图像)的更多信息,这些信息只能使用内容可编辑的 div 进行访问,但我不是很清楚。

最佳答案

我们的魔法酱汁是:

$('body').bind('paste', handlepaste);

handlepaste 与您的非常相似,因此对于 Chrome 应该适合您。

不幸的是,上述对于 FF 完全失败,我们不愿意在任何地方添加 contenteditable(特别是考虑到它必须才能工作并且我们不想抢走焦点)。

关于javascript - 如何在 webkit 浏览器中访问粘贴的文件? (如谷歌浏览器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27262428/

相关文章:

google-chrome - 如何在新窗口中打开Chrome开发者工具?

css - 强制 Chrome 在 CSS 中使用外部字体

python - selenium.common.exceptions.WebDriverException : Message: Can not connect to the Service error using ChromeDriver Chrome through Selenium Python

python - 动态地从 PIL 提供图像

excel - 在 vba 上将值粘贴到另一个工作簿工作表上时出现问题

javascript - 如何让Gulp完成一项任务,然后才开始下一项任务

javascript - Mac OS X——如果 chrome/firefox/safari 处于全屏模式,我可以用 javascript 检测吗?

jQuery Ajax : Copy - Paste thingy

javascript - 如何使用javascript获取字符串的一部分?

javascript - 如何将数据加载到 Javascript 对象中