Search code examples
javascriptgoogle-chrome-extension

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.


Solution

  • 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.sstatic.net/C4ndg.jpg"});
        }
    });