Content scripts

Make page changes reversible

Insert one accessible note panel without corrupting page markup, duplicating UI, or leaving changes the user cannot undo.

8 minute lesson

~~~

A content script is a guest in someone else’s document. Its DOM changes should be minimal, namespaced, and reversible.

Create elements with DOM APIs, render note text with textContent, use unique prefixed IDs or a shadow root, and remove an existing panel before inserting another. Include a close button and restore any page state you change.

Prefer adding one extension-owned root over rewriting page HTML. A shadow root can reduce style collisions, but it does not hide content from the page and it still needs accessible names, focus styles, and sensible colors. Namespaced light-DOM CSS is simpler when isolation needs are small.

Track every side effect: inserted nodes, event listeners, classes, inline styles, scroll locking, and focus changes. Reversal means removing or restoring each one. Store original values before mutation and do not assume the page kept them unchanged while your panel was open.

Repeated show messages should update the existing panel rather than create duplicates. Closing should return focus to a meaningful page or extension control when possible, and removal by the host page should not crash later message handling.

Build a fixed note panel with a labelled close button. Show it repeatedly with changing text, close it, let page code remove it, and show it again. Compare the DOM before and after: no duplicate IDs, orphaned listeners, global style changes, or interpreted note markup should remain.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →