javascript - 通过 chrome 扩展从 URL 上传图片
问题描述
我正在尝试构建可以将图像从 URL 上传到任何输入的 chrome 扩展:类型。这是 100% 可能的,因为我找到了一个实现我想要的扩展。
此扩展查找文件类型的所有输入。然后,您只需从远程服务器粘贴指向图像的链接。
我需要可以用 URL 中的图像填充已知 input:file 的代码。
解决方案
我的用例有点不同(在后台自动上传),但无论如何我都能像这样工作......
content_script.js
async function createFile(url: string) : Promise<File> {
let response = await fetch(url);
let data = await response.blob();
let metadata = {
type: 'image/jpeg'
};
return new File([data], "test.jpg", metadata);
}
chrome.runtime.sendMessage({load: "true"},async function(response) {
if (response.url) {
const designFile = await createFile(response.url);
// find the file input element and trigger an upload
const input = document.querySelector('input.jsUploaderFileInput') as HTMLInputElement;
const dt = new DataTransfer();
dt.items.add(designFile);
input.files = dt.files;
const event = new Event("change", {
bubbles: !0
});
input.dispatchEvent(event)
}
});
背景.js
chrome.tabs.create({url: 'https://www.somepagewithanuploadform.com'});
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.load == "true") {
sendResponse({url: "https://i.stack.imgur.com/C4ndg.jpg"});
}
});
推荐阅读
- java - Android Studio 中的突然编译错误;错误:找不到符号类 ComputableLiveData
- javascript - 如何从浏览器控制台检索记录的数据到 http 服务器
- wordpress - WordPress Post Meta 而不是自定义帖子类型中的标题
- perl - Perl 有交互式命令行环境吗?
- php - 将十进制数存储到 MySQL 数据库中
- scala - Is parameter evaluation order guraanteed in scala?
- java - 如何在mybatis的IN子句中使用超过1000个args?
- jquery - 用于更改特定文本数据的背景颜色的 Jquery 代码
- sql-server - 在 XML 元素外加入 Temp 表
- java - KEYCODE_ENTER - 如何?