Chrome扩展:将下载的文件移动到输入字段

Chrome extension: move downloaded file to input field

本文关键字:移动 输入 字段 文件 扩展 下载 Chrome      更新时间:2024-04-29

我正在尝试用我构建的一个小chrome扩展迁移图像。扩展名由5个文件组成:

popup.html-插件html文档

 Has some html buttons
also has script link to my settings.js file that listens for the image downlaod button to be clicked and send a message to my content script : run.js to find the images

run.js-内容脚本(可以访问网页DOM)。

This script recieves the message from run.js which then finds all the images names and image links i want to download. It puts them into an object and sends them via message to the backgorund script : bootstrap.js

bootstrap.js-运行后台页面并可以访问chromeapi。

var Downloads = [];
chrome.extension.onMessage.addListener(function(request, sender, sendResponse)
{
if(request.message.method == 'download'){
    for( var d = 0; d <= request.message.imageLinks.length; d++ ){
      chrome.downloads.download( {url: request.message.imageLinks[d],
             filename: request.message.imageName[d]}, function(id){
        });
          sendResponse('done');
    }
}
}); 

这一切都很好用。它循环浏览图像并下载它们。我现在需要做的是:取我刚刚下载的图像,并将它们插入其他网站上的文件上传字段(我在另一个选项卡中打开了该字段),这些字段具有相同的字段名称等等。。我看到chrome有

//Initiate dragging the downloaded file to another application. Call in a javascript ondragstart handler.
chrome.downloads.drag(integer downloadId)

起初,我认为这可能会起作用,因为您可以手动将下载的图像拖动到html文件上传字段中,而无需单击并选择文件。但我在上面找不到任何文档/例子。

有人知道用javascript/chrome api可以实现这一点吗?

首先需要访问下载的文件的内容。

为此,您需要在清单文件中添加对file://*的权限。然后,您可以使用例如chrome.downloads.search循环浏览下载的文件,并获取每个文件在系统中的路径(DownloadItem.filename属性)。对于每个文件,对url file://{filepath}进行GET XMLHttpRequest以获取文件的内容。

一旦您有了这些内容,您就可以将其转换为DataUrl,并以编程方式将该文件添加到表单的FormData中(但不是实际输入,只是最后提交的FormData)。请参阅此部分的答案。