Subscribe

Browser extensions - Modify images on the page

✍️

How to replace all images on a webpage with a popup browser extension

28 Aug, 2022 · 2 min read

This article will examine how we can modify images on the active page.

If you’d like to follow along with the article, use the following GitHub branch as your starting point.

Below is a video of today’s article code in action. You can see we replace all images on an IMDB page with kittens.

Modify all images on the page

As usual, we must register a new button in our popup menu. This button will be the invocation for changing all the images on the page. Open up the src/App.jsx file and add the following content:

<button onClick={imageSpoof}>Change images</button>

We’ll need to use the scripting we learned about in the previous article to inject a function on the page.

const imageSpoof = async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: spoofImages,
  });
};

With this in place, we can create the actual spoofImages function we defined.

const spoofImages = () => {
  const images = document.getElementsByTagName('img');
  for (const image of images) {
    image.removeAttribute('srcset');
    image.src = 'http://placekitten.com/300';
  }
};

This will replace all images on the page with a kitten placeholder. I also decided to remove the srcset simply because it would take higher priority.

Note: This will currently place the same kitten image everywhere.

And that’s it, and we can now replace images on every website we visit.

You can find the completed code on GitHub.

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Browser extensions - recap and status

1 Sep, 2022 · 2 min read

Browser extensions - recap and status

Browser extensions - DevTools extension

31 Aug, 2022 · 2 min read

Browser extensions -  DevTools extension

Join 2099 devs and subscribe to my newsletter