Search code examples
javascriptgoogle-chrome-extensionfirefox-addonbrowser-extension

Remove HTML via clicking Browser Action after adding it to DOM in Chrome Extension?


I want to create something like Font Face Ninja where I click on the browser action & it loads a UI & after clicking again it removes the UI.

My minimal reproduction is as follows -

manifest.json

{
  "manifest_version": 2,
  "name": "Sample",
  "version": "1.0.0",
  "description": "Sample Extension",
  "icons": {
    "16": "icon16.png",
    "32": "icon32.png",
    "48": "icon48.png",
    "128": "icon128.png"
  },
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {},
  "permissions": ["activeTab", "https://*/*", "http://*/*"]
}

content.js

const body = document.getElementsByTagName('body')[0]

const div = document.createElement('div')
div.innerHTML = `<h1>Sample Extension</h1>`
body.appendChild(div)

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(tab.id, {
    file: 'content.js',
  })
})

The above example appends <h1>Sample Extension</h1> to any page. This is my UI.

I want to remove that when browser action is clicked again. How do I do that?


Solution

  • The HTML can be removed easily by doing body.removeChild(div) in content.js.

    However, I wanted it togglable which must be done using message passing so I posted a solution to make it togglable so it adds HTML to the DOM when clicked once & removes it when clicked again & so on.

    Find the solution here → https://stackoverflow.com/a/57179116/6141587

    I've also uploaded the repo containing both Browser Action & Page Action (check branch page_action) to Github → https://github.com/deadcoder0904/insert-remove-ui-chrome-extension/