How to write a string replacement browser plugin

browser plugin javascript Firefox Chrome

2 min read | by Jordi Prats

If you want to write a browser plugin that replaces strings on webpages the easiest method is by doing it using Javascript. So, to replace a in a webpage a string for another we can use the following Javascript code:

document.body.innerHTML = document.body.innerHTML.replace(/\bA\b/g, "B");

Writing a plugin for Firefox and Google Chrome will have it's subtle differences, but in the end the important bit that does the work is going to be the same code

For Chrome we will have to write a manifest.json that will tell the browser which code to run and that's pretty much it:

{
  "manifest_version": 2,
  "name": "mispellings fixer",
  "version": "1.0",
  "description": "Fix common misspellings for Is Pain",
  "icons": {
      "48": "data/icon.png"
  },
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": ["content.js"]
    }
  ]
}

While for Firefox we will have to also zip the contents (XPI file) :

zip -r -FS ./ispain.xpi * --exclude '*.git*' --exclude '*.sh' --exclude '*.zip' --exclude '*.xpi'

Either way we are just telling the browser what needs to be run for each page in order to replace the strings we want to fix.


Posted on 12/10/2021