简体   繁体   中英

Upload image from URL via chrome extension

I'm trying to build chrome extension that can upload image from URL to any input:type. It is 100% possible because i found one extension which implements that i want.

Link to this extension: https://chrome.google.com/webstore/detail/upload-image-from-url/eiglgndkjiabiepkliiemoabepkkhacb?hl=en

This extension finds all inputs of file type. Then you just need to paste a link to image from remote server.

screenshot of this extension 1

screenshot of this extension 2

I need the code which can fill known input:file with image from URL.

My use case was a little different (to automate some uploading in the background), but in any case I was able to get this working like so...

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM