Write a "cloud" to "butt" Chrome extension in three minutes

programming to glassblowing

Writing a chrome extension to replace words on a webpage is easy. Follow these 5 steps to make one.

Step 1: Create a directory called "myChromeExtension".

mkdir myChromeExtension
cd myChromeExtension

Step 2: Create the file "manifest.json" and copy the following into it.

    {
        "manifest_version": 2,
        "name": "Word Replacer",
        "version": "1.0",
        "description": "Replace [word 1] with [word 2].",
        "content_scripts": 
        [
            {
                "matches": ["*://*/*"],
                "js": ["content_script.js"],
                "run_at": "document_end"
            }
        ]
    }
            

Step 3: Createe the file "content_scripts.js" and copy the following.

    walk(document.body);

    function walk(node) 
    {var child, next;

        switch ( node.nodeType )  
        {
            case 1:  // Element
            case 9:  // Document
            case 11: // Document fragment
                child = node.firstChild;
                while ( child ) 
                {
                    next = child.nextSibling;
                    walk(child);
                    child = next;
                }
                break;

            case 3: // Text node
                handleText(node);
                break;
            default:
                break;
        }
    }

    function handleText(textNode) 
    {
        var text = textNode.nodeValue;

        text = text.replace(/programming/g, "glassblowing");
        text = text.replace(/Programming/g, "Glassblowing");
        text = text.replace(/PROGRAMMING/g, "GLASSBLOWING");

        text = text.replace(/TRUMP/g, "DUCK");
        text = text.replace(/Trump/g, "Duck");

        text = text.replace(/\bHacker\b/g, "Pooper");
        text = text.replace(/\bhacker\b/g, "pooper");
        text = text.replace(/\bHACKER\b/g, "HACKER");
        
        textNode.nodeValue = text;
    }
            

Step 4: Open the Chrome browser and type chrome://extensions/ into the address bar. Click the checkbox to enable "Developer mode".

Step 5: Click on "Open unpacked extension" and select the directory "myChromeExtension".

You are done! Now go browse the internet!

trump to duck hacker to pooper

Further reading

  1. More on making Chrome extensions.
  2. See panicsteve's github for source files.
  3. Learn more about regular expressions.