How to Replace Images in a Website with your own using Chrome Extension | Chapter-6

Heptagon Perspectives
Heptagon
Published in
6 min readMar 11, 2019

In “How to Build a Chrome Extension Series”, we are learning how to build a Chrome Extension from scratch and also learn how to add some basic customizations to these extensions. Note: 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 on a website with your own images using Chrome Extension.

Replacing Image using chrome extension

Table of Contents

  • Requirements
  • The Workflow
  • Initializing The Chrome Extension
  • The Output
  • Summary

Requirement

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

Image Storage Folder

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.

Code Files

To create a Chrome Extension that replaces all the images on 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 on 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 the source to popup.html. So we don't 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;
}
}l look something like this

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 on the website with our selected image.

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

Initializing The Chrome Extension

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

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.

Replacing image
  • Click on Submit and all the images on 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

I hope, the sixth chapter was able to help you replace images on 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.

Originally published at https://heptagon.in

--

--

Heptagon Perspectives
Heptagon

We are #heptagon. A dynamic, multi-faceted polygon. A passionate group of #business and #technology experts building scalable and global technology solutions.