提供文件数据时触发“drop”事件

old*_*god 4 javascript dom-events

问题

我如何在提供文件时触发一个drop字段事件,而我在加载时无权访问该字段

细节

有一个页面,其中有一个字段,该字段上附加了一个drop侦听器,该侦听器在放置时处理图像。我希望能够通过粘贴图像来使用此过程。我知道如何从粘贴中获取文件,但我不知道如何调度drop包含该文件的事件。

障碍是:

  • 代码被混淆了,我无法访问通过名称与侦听器链接的函数。
  • drop在将侦听器附加到元素后,无法获取侦听器。似乎有某种方法可以在控制台中执行此操作,但不能通过脚本执行此操作。
  • 我不控制页面渲染;即我无法拦截事件侦听器添加。
  • Vanilla Javascript & 只能在 Chrome(扩展)中工作。
  • 此页面是用香草构建的;即没有 jQuery 或任何东西。

有谁知道如何完成这项任务?

我正在研究DragEvent,“尽管此接口有一个构造函数,但不可能从脚本创建有用的 DataTransfer 对象,因为 DataTransfer 对象具有在拖放过程中由浏览器协调的处理和安全模型。”

我看到了一种可能的方法/sf/answers/2734651041/,但我想用其数据模拟真实的放置事件,即传递我通过获得的文件clipboardData.items[0].getAsFile();而不仅仅是文本。

Jul*_*ire 6

您可以伪造掉落事件,并伪造其中的几乎所有内容。您会遇到的问题是触发默认事件,例如通过拖放文件来打开选项卡中的文件。原因并不是因为dataTransfer对象受到保护,而是因为事件不受信任。通过拥有受信任的事件和受保护的 dataTransfer,您可以确保不会将数据传递给受信任的事件,并且不会使用不需要的数据触发默认事件。

但根据 drop 函数如何访问被删除的文件,您可能可以使用假drop事件和假dataTransfer对象来欺骗它。请参阅此小提琴以了解其工作原理的一般概念:

var a = document.getElementById('link');
var dropZone1 = document.getElementById('dropZone1');
var dropZone2 = document.getElementById('dropZone2');
var fakeDropBtn = document.getElementById('fakeDropBtn');

dropZone1.addEventListener('dragover', function(e) {
  e.preventDefault();
});

dropZone2.addEventListener('dragover', function(e) {
  e.preventDefault();
});

dropZone1.addEventListener('drop', function(e) {
  // This first drop zone is simply to get access to a file.
  // In your case the file would come from the clipboard
  // but you need to work with an extension to have access
  // to paste data, so here I use a drop event
  e.preventDefault();
  fakeDropBtn.classList.remove('disabled');
  dropZone2.classList.remove('disabled');
  var fileToDrop = e.dataTransfer.files[0];

  // You create a drop event
  var fakeDropEvent = new DragEvent('drop');
  // You override dataTransfer with whichever property
  // and method the drop function needs
  Object.defineProperty(fakeDropEvent, 'dataTransfer', {
    value: new FakeDataTransfer(fileToDrop)
  });

  fakeDropBtn.addEventListener('click', function(e) {
    e.preventDefault();

    // the fake event will be called on the button click
    dropZone2.dispatchEvent(fakeDropEvent);
  });
});



dropZone2.addEventListener('drop', function(e) {
    e.preventDefault();
  // this is the fake event being called. In this case for 
  // example, the function gets access to dataTransfer files.
  // You'll see the result will be the same with a real
  // drop event or with a fake drop event. The only thing
  // that matters is to override the specific property this function
  // is using.
  var url = window.URL.createObjectURL(e.dataTransfer.files[0]);
  a.href = url;
  a.click();
  window.URL.revokeObjectURL(url); 
});

function FakeDataTransfer(file) {
  this.dropEffect = 'all';
  this.effectAllowed = 'all';
  this.items = [];
  this.types = ['Files'];
  this.getData = function() {

    return file;
  };
  this.files = [file];
};
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/5m2u0tux/6/