首页 > 解决方案 > 通过 chrome 扩展从 URL 上传图片

问题描述

我正在尝试构建可以将图像从 URL 上传到任何输入的 chrome 扩展:类型。这是 100% 可能的,因为我找到了一个实现我想要的扩展。

链接到这个扩展:https ://chrome.google.com/webstore/detail/upload-image-from-url/eiglgndkjiabiepkliiemoabepkkhacb?hl=en

此扩展查找文件类型的所有输入。然后,您只需从远程服务器粘贴指向图像的链接。

此扩展程序的屏幕截图 1

此扩展程序的屏幕截图 2

我需要可以用 URL 中的图像填充已知 input:file 的代码。

标签: javascriptgoogle-chrome-extension

解决方案


我的用例有点不同(在后台自动上传),但无论如何我都能像这样工作......

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"});
    }
});

推荐阅读