How to Write Userscripts from Scratch?
Learning to write custom userscripts allows you to modify web pages, automate repetitive actions, and enhance your browsing experience using JavaScript. This guide provides an overview of setting up a script manager, writing the essential metadata block, crafting custom code to manipulate the Document Object Model (DOM), and debugging your creation directly in the browser.
Step 1: Install a Userscript Manager
Before writing code, you need a browser extension to run and manage your scripts. Popular, open-source script managers include:
- Tampermonkey: Available for Chrome, Firefox, Edge, and Safari.
- Violentmonkey: A lightweight option available for major browsers.
- Greasemonkey: The original manager, primarily focused on Firefox.
Once installed, clicking the extension icon gives you access to a dashboard where you can create, edit, and toggle your custom scripts.
Step 2: Create a New Script and Understand Metadata
Open your manager’s dashboard and select Create a new script. Every userscript starts with a specific comment block known as the Metadata Block. This tells the extension when and where to execute your JavaScript.
Here is a standard metadata block template:
// ==UserScript==
// @name My First Userscript
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Customizes specific web pages to improve UI.
// @author Your Name
// @match https://example.com/*
// @grant none
// @run-at document-end
// ==UserScript==Key directives include:
@name: The display title of your script.@match: Defines which URLs trigger the script. You can use wildcards (e.g.,*).@run-at: Controls execution timing, such asdocument-start,document-end, ordocument-idle.@grant: Requests special manager permissions, such as cross-origin HTTP requests (GM_xmlhttpRequest) or key-value storage (GM_setValue). Set tononefor simple DOM modifications.
Step 3: Write Your JavaScript Code
Below the metadata block, write standard JavaScript to interact with the target webpage. Wrapping your code in an Immediately Invoked Function Expression (IIFE) prevents variable collisions with the page’s native scripts.
(function() {
'use strict';
// Target a specific element on the webpage
const targetHeader = document.querySelector('h1');
if (targetHeader) {
// Change text content and styling
targetHeader.innerText = 'Customized Webpage!';
targetHeader.style.color = '#007BFF';
}
})();Step 4: Handle Dynamic Page Content
Modern websites load content asynchronously using frameworks like
React or Vue. If your script runs before elements appear on the page,
target elements might return null. You can handle dynamic
elements using a MutationObserver:
(function() {
'use strict';
const observer = new MutationObserver((mutations, obs) => {
const element = document.querySelector('.dynamic-element');
if (element) {
element.style.display = 'none'; // Hide element once loaded
obs.disconnect(); // Stop observing after execution
}
});
observer.observe(document.body, { childList: true, subtree: true });
})();Step 5: Save and Test
- Save the file inside your script manager editor.
- Navigate to the website specified in your
@matchdirective. - Open Developer Tools (
F12orCtrl+Shift+I/Cmd+Option+I) to monitor console logs, errors, and inspect modified DOM elements.