Subscribe

Browser extensions - Popup page modifications

✍️

Modifying the active tab through a browser popup extension

26 Aug, 2022 · 3 min read

We already created a basic extension that made all the websites we visit pink, but what if we want that action to only happen when we click a button inside our popup extensions?

Well, in this article, we’ll learn just that, and even better, we base the color of our local storage that we implemented in a previous article.

If you wish to follow this article, use this GitHub branch as your starting point.

What we want to achieve today is that by clicking a button inside our popup extension, the color of the active tab changes.

We’ll first need to add some new permissions to our manifest.json file.

{
  "permissions": ["alarms", "notifications", "storage", "activeTab", "scripting"],
}

The new ones are activeTab and scripting. Which do the following:

  • activeTab allows us to modify and retrieve the active tab
  • scripting allows us to inject scripts via the browser

Now let’s go ahead and modify our popup page. Open the src/App.jsx file and add a button in the render section.

return <button onClick={colorize}>Colorize 💖</button>;

Now let’s add this colorize function.

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

This looks super complicated, but don’t worry. I’ll guide you through this.

First, we need to fetch the active tab. We can use the tabs query for this.

Once we have the active tab, we can invoke the chrome scripting API. We call the executeScript function, which can inject a script or simple function on that tab. In our case, we inject the changeColor function.

We can then add this function to this file to be used.

const changeColor = () => {
  chrome.storage.sync.get('color', ({ color }) => {
    document.body.style.backgroundColor = color;
  });
};

This function will read out local storage and grab the color from it. Then we’ll set the documents body to that color.

And voila! With the click of a button, you’re able to change any website!

Note: Remember that we added the colors in local storage? You can play around by changing the color in your options.

You can also find the complete 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 2097 devs and subscribe to my newsletter