Chrome Extension replace images
Do It Yourself Technology

How to Build a Chrome Extension | Chapter 6: How to replace images in a website

In “How to Build a Chrome Extension” series, we will learn how to build a Chrome Extension from scratch and also learn how to add some basic customizations to these extensions. Feel free to skip to any chapter by clicking on the links provided at the end of this post. For now, here are the Contents of Chapter 6: Replacing images in any webpage using  Chrome Extension.

Contents

Requirements

In this chapter, we are going to create a chrome extension that replaces the images in a webpage with user-given images by selecting images from a dropdown list.

Image Storage Folder

The images that are to be selected to be replaced with the webpage images have to be stored in a folder. Refer the Chapter 2 for creating a folder or a file.

  • Copy some images of your choice to the folder (For Chrome extension icon)
  • Let’s create a folder called images and copy some images into it in .jpg format.
replace images in a website chrome extension

Code Files

To create a Chrome Extension that replaces all the images in the web page with our own images (by selection), we require the following files.

  • manifest.json: Contains the configurations, properties, and information about the Chrome Extension.
  • popup.html: Pops up with a message when the Chrome extension is clicked.
  • popup.js: Contains the content script that communicates with the popup.
  • content.js: Contains the content that needs to be performed on chrome.

Step 1: Create the manifest.json file with the following code.

{
  "manifest_version" : 2,
  "name" : "Chrome-Extension: replace Image",
  "version" : "0.1",
  "web_accessible_resources" : [
     "images/*.jpg"
  ]
}

Step 2: The popup.html file will contain the following code for a dropdown list and a submit button. The dropdown list will contain all the images which are stored in the images folder. When we select an image in the dropdown list and click submit, the images in the web page will be replaced with the image that we have selected.

<!DOCTYPE html>
  <script src="background.js" type="text/javascript"></script>
  <script src="merged.js" type="text/javascript"></script>

  <body>

  <h5>Select an image and Replace!</h5>
  <form>
    <select name="images" id="select_image">
      <option value="image1" id="image_kitten">Kitten</option>
      <option value="image2" id="image_puppy">Puppy</option>
      <option value="image3" id="image_panda">Panda</option>
      <option value="image4" id="image_deer">Deer</option>
      <option value="image5" id="image_rabbit">Rabbit</option>
    </select>
    <br />
    <button type="button" id="button_submit">Submit</button>
    <br>
  </form>
</body>

Step 3: The manifest.json has to be updated with popup.html as the default popup for browser action. The updated manifest.json will look something like this.

{
"manifest_version" : 2,
"name" : "Chrome-Extension: replace Image",
"version" : "0.1",
"web_accessible_resources" : [
"images/*.jpg"
],
"browser_action" : {
"default_icon" : "r.png",
"default_popup" : "popup.html"
}
}

Step 4: Let’s create a script popup.js. This content script communicates with the popup. The popup.js gets the results from the popup and sends the action message to the popup.js script. The popup.js will contain the following code 

document.addEventListener('DOMContentLoaded', function () {
var submitButton = document.getElementById('button_submit');
submitButton.addEventListener('click', sendData);
});
function sendData() {
  let params = {
  active: true,
  currentWindow: true
 }
chrome.tabs.query(params, gotTabs);
function gotTabs(tabs) {

var selected = document.getElementById("select_image");
var selectedImage = selected.options[selected.selectedIndex].value;
let message = {
txt: "Hello",
selectedImage: selectedImage
}
chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
console.log("Success");
});
}
}

Note: We have added background script as source to popup.html. So we dont have to add it to manifest

Step 5: The content.js script performs the replace image action with the selected image. In the following code, we will be receiving a message from popup.js and will call the replace function to replace the image.

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.txt == "Hello") {
replace(message.selectedImage, sender, sendResponse);
}
});
function selectAndReplace(message, sender, sendResponse) {
let imgs = document.querySelectorAll('img');

switch (message) {

case "image1":
for (imgElt of imgs) {
let file = 'images/kitten.jpg';
let url = chrome.extension.getURL(file);
imgElt.src = url;
}
break;
case "image2":
for (imgElt of imgs) {
let file = 'images/puppy.jpg';
let url = chrome.extension.getURL(file);
imgElt.src = url;
}
break;

case "image3":

for (imgElt of imgs) {
let file = 'images/panda.jpg';
let url = chrome.extension.getURL(file);
imgElt.src = url;
}
break;
case "image4":
for (imgElt of imgs) {
let file = 'images/deer.jpg';
let url = chrome.extension.getURL(file);
imgElt.src = url;
}
break;
case "image5":
for (imgElt of imgs) {
let file = 'images/rabbit.jpg';
let url = chrome.extension.getURL(file);
imgElt.src = url;
}
break;
}
}

Step 6: The final manifest.json file will look something like this

{
"manifest_version" : 2,
"name" : "Chrome-Extension: replace Image",
"version" : "0.1",
"web_accessible_resources" : [
"images/*.jpg"
],
"content_scripts" : [
{
"matches" : [
"<all_urls>"
],
"js" : ["content.js"]
}
],
"browser_action" : {
"default_icon" : "r.png",
"default_popup" : "popup.html"
}
}

The Workflow

After we click the Chrome Extension icon, the popup appears. The popup contains two fields, a drop down list and a submit button. The drop down field contains the images which can be chosen to replace, after selecting which we click the submit button.

Submit button click sends a message to the popup.js file which in turn sends a message to the content.js script and the content script then replaces the images in the website with our selected image.

Initializing The Chrome Extension

After all the files for the Chrome Extension are created and filled with the given codes, to add the Chrome Extension to your browser perform the following steps.

Step 1: Go to Google Chrome and type chrome://extensions in the address bar.

Step 2: Enable Developer Mode option on the top right corner of the page.

Step 3: Click the Load unpacked button.

Step 4: Select the folder where we have written the code and click open.

Now the Chrome Extension is loaded into the browser.

Chrome Extension loaded replace images in a website

BrowserAction: Use browser actions to put icons in the main Google Chrome toolbar, to the right of the address bar. In addition to its icon, a browser action can have a tooltip, a badge, and a popup.

Note: Even if you don’t specify a browser action icon, a default icon with the letter of the name of your extension (given in manifest) will be assigned.

The Output

  • Now open any web page which contains images and open the console using ctrl+shift+j. You can see the message saying “We are ready to replace the images!”. If the page is already open. refresh it!
Chrome Extension Ch 6 replace images in a website
  • When we click our Chrome Extension icon (right side of the address bar) we can see a dropdown list and then we can select any of the images.
Chrome Extension the output replace images in a website
  • Click on Submit and all the images in the webpage will be replaced with the image that we had selected when we clicked the Chrome Extension icon.
Chrome Extension replace images in a website the output 2

Summary

Hope, the sixth chapter was able to help you replace images in a webpage with the image that we selected from the list of images that we have already saved in our folder.

In the next chapter, we’ll be learning how to deploy and publish a Chrome Extension in the Chrome Web store. Feel free to reach out for any queries.


Chapter Navigation

Chapter 1: An Introduction to Extensions

Chapter 2: Bookmarklets

Chapter 3: Changing the background color of a paragraph with Chrome Extension

Chapter 4: Replacing paragraph text with your user-given text using Chrome Extension

Chapter 5: Replacing images in a website using Chrome Extension

Chapter 6: Replacing images with your own images using Chrome Extension

Chapter 7: Deploy and Publish your Chrome Extension

Chapter 8: The Atomic Habit Tracker

References

Leave a Reply

Your email address will not be published. Required fields are marked *

fourteen − four =