[英]Trigger 'drop' event while providing the file data
题
我怎么能在提供文件的同时触发一个字段的drop
事件,我在 loading 时无权访问该字段。
细节
有一个带有字段的页面,该页面上附加了一个drop
侦听器,该侦听器在放置时处理图像。 我希望能够通过粘贴图像来使用此过程。 我知道如何从粘贴中获取文件,但我不知道如何分派包含此文件的drop
事件。
障碍是:
drop
侦听器附加到元素后,无法获取它。 似乎有某种方法可以在控制台中执行此操作,但不能通过脚本执行此操作。有没有人知道如何处理这项任务?
我正在研究DragEvent,但是“虽然这个接口有一个构造函数,但不可能从脚本创建一个有用的 DataTransfer 对象,因为 DataTransfer 对象有一个处理和安全模型,在拖放过程中由浏览器协调。”
我看到了一种可能的方法https://stackoverflow.com/a/39066443/1004274,但我想用它的数据模拟一个真正的放置事件,即传递我通过clipboardData.items[0].getAsFile();
获得的文件clipboardData.items[0].getAsFile();
而不仅仅是文本。
您可以伪造drop事件,并伪造其中的几乎所有内容。 您将遇到的问题是触发默认事件,例如通过删除选项卡中的文件来打开它。 原因不是因为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];
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.