Google chrome rehost image extension
Asked Answered
B

1

3

I would like to have a Google Chrome extension to rehost any image I click on.

For example, I have a html document with images using <img> tag. I want to have a extension which will rehost that image to an another image host. I saw something like this with the imgur extension. I have no clue where should i begin or what should I do to get this work.

Thanks for your help in advance!

Bartolemo answered 7/7, 2012 at 21:6 Comment(0)
R
3

First, you have to get an API key. If a maximum of 50 uploads per hour is sufficient, and you don't want to register an account, get an anonymous API key.

Instead of binding a left-click event handler, which may interfere with a page, I suggest to add a contentmenu entry using the chrome.contextMenus API.

Manifest file, manifest.json:

{
  "name": "Rehost img at imgurl",
  "version": "1.0",
  "manifest_version": 2,
  "background": {"scripts":["background.js"]},
  "permissions": [
    "contextMenus",
    "http://*/*", // This permission is needed to fetch URLs
    "https://*/*"
  ]
}

Put the following code in your background script (using chrome.contextMenus.create):

// background.js
chrome.contextMenus.create({
    title: "Rehost image",
    contexts: ["image"],
    onclick: function(info) {
        // Get the image from cache:
        var x = new XMLHttpRequest();
        x.onload = function() {
            // Create a form
            var fd = new FormData();
            fd.append("image", x.response); // x.response = blob
            fd.append("key", "API KEY HERE");

            // Now, upload the image
            var y = new XMLHttpRequest();
            y.onload = function() {
                var url = JSON.parse(xhr.responseText).upload.links.imgur_page;
                // Now, do something with the new url.
            };
            y.open('POST', 'http://api.imgur.com/2/upload.json');
            y.send(fd);
        };
        x.responseType = 'blob';    // Chrome 19+
        x.open('GET', info.srcUrl); // <-- info.srcUrl = location of image
        x.send();
    }
});

You could display the URL to the user (simpliest method is prompt("Here's the URL:",url);, or use localStorage to map the previous URL to the new host and/or use the chrome.webRequest API to redirect the image requests to the new host.


Using a different web service / image host to upload the picture. http://picstore.eu/ does not provide an API, so we submit a form programatically.

// background.js
chrome.contextMenus.create({
    title: "Rehost image",
    contexts: ["image"],
    onclick: function(info) {
        // Get the image from cache:
        var x = new XMLHttpRequest();
        x.onload = function() {
            var file_name = info.srcUrl.split(/[?#]/)[0].split('/').pop();
            var fd = new FormData();
            fd.append("imgUrl", "");
            fd.append("fileName[]", file_name);
            fd.append("Search files", "Browse");
            fd.append("file[]", x.response, file_name);
            fd.append("alt[]", file_name.replace(/[-_]/g, " ").replace(/\.[^.]*$/, ""));
            //fd.append("private[0]", "1"); // "Private images.."
            //fd.append("shorturl[0]", "1"); // "Create short URLs using b54"
            fd.append("new_height[]", "");
            fd.append("new_width[]", "");
            fd.append("submit", "Upload");
            var y = new XMLHttpRequest();
            y.responseType = 'document'; // Chrome 18+ (but blob is 19+)
            y.onload = function() {
                var url = y.response.getElementById('codedirect').value;
                prompt("URL:", url);
                // Now, do something with the new url.
            };
            y.open('POST', 'http://picstore.eu/upload.php');
            y.send(fd);
        };           
        x.responseType = 'blob'; // Chrome 19+
        x.open('GET', info.srcUrl); // <-- info.srcUrl = location of image
        x.send();
    }
});
Rosalynrosalynd answered 8/7, 2012 at 9:40 Comment(8)
The point is that i do not need to rehost on imgur but on my own image hosting site. That is powered by code future image host i would implement that.Bartolemo
@user1430562 The exact implementation depends on the API offered by your host. The basic remains equal: 1. Retrieve the image from cache 2. Submit the binary data to the web service using a FormData object.Rosalynrosalynd
And if the specific image host hasnt any api then i could not do this?Bartolemo
@user1430562 Yes you can. FormData simulates a form submission. .append('blabla',Blob/File) is similar to <input type="file" name="blabla">. .append('foo','bar') is equivalent to <input name='foo' value='bar'>. With minimal efforts, you should be able to create and submit a form using FormData.Rosalynrosalynd
Yes but i never coded in this syntax so i don't really know how to make it workBartolemo
You should have mentioned that right away... Add more details to the question regarding the web service and your level of knowledge, and I might give it another try.Rosalynrosalynd
Thanks for this i have made on my local machine a folder i put there: manifest.json and background.js The manifest.json contents are these what you have posted in your first answer and the background.js contents are these what at the pastebin.com url and therefore it is not workingBartolemo
@user1430562 Updated answer with code. I have successfully tested the extension with the gravatar image, at the bottom of the answer.Rosalynrosalynd

© 2022 - 2024 — McMap. All rights reserved.