DEV Community

Cover image for Browser extensions - Popup page modifications
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Browser extensions - Popup page modifications

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.

Popup extension modifies a page

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

Browser extensions - Popup page modifications

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

{
  "permissions": ["alarms", "notifications", "storage", "activeTab", "scripting"],
}
Enter fullscreen mode Exit fullscreen mode

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>;
Enter fullscreen mode Exit fullscreen mode

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,
  });
};
Enter fullscreen mode Exit fullscreen mode

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;
  });
};
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)