Chrome Extension: Remove unwanted Elements

Pnk
2 min readJun 20, 2022

--

Remove unwanted elements

This Chrome Extensions basically removes the DOM elements from the page on click of it.

Recently started exploring ways to start building a chrome extension and felt that extension manipulating DOM will be the best place to start learning.

In that direction, built this, where, on hover of DOM elements, will be adding a border styling and on click of that element, changing the opacity to 0 so that the element will be hidden keeping the layout of the page intact.

The main starting point of chrome extension is manifest file, where the extension’s meta data is mentioned, such as

1. Extension’s name

2. Description (of extension)

3. permission’s (such as storage, tab etc) (in this extension no permission was required)

4. background js (this file will be executing in background and will listen to event such as extension icon clicked)

5. content scrips (this js file has access to DOM and can modify DOM) (the hero in this component) etc etc

Entry Point of Extension

As background.js is running continuously in the background of chrome browser, it can be used to listen any events that is triggered at any point of time and can be used to activate the extension.

Here chrome extension API is used to add a click event handler on extension icon, and the click handler, queries active tab from all the opened tabs and send a custom message, which will be listened in content script to activate itself as shown below.

On receiving the message remove_element_clicked_browser_action, it activates itself by adding relevant Event Listener (hover and click events) and creating a DOM elements with two actionable item (Undo Remove and Close Extension). The first time its get called it attach the event (activates itself) and the second time its triggered it remove the attached event (deactivates itself). Here it is handled by maintaining a flag isActionClicked.

Also a list of last 5 hidden elements is maintained in listOfHiddenElems array so that the user can undo the remove action for last 5 actions.

For more details, complete code can be found here.

I have also published the extension, feel free to checkout and leave feedback.

Reference article that help in building the extension is chrome official website

Will try to build more extension and share the journey here.

--

--