Can Userscripts Inject Custom CSS Into Webpages?

Userscripts can inject custom CSS into a webpage to alter its appearance, hide unwanted elements, or create personalized themes. By utilizing specialized API functions provided by browser extensions like Tampermonkey or Violentmonkey, or by manually appending <style> tags directly into the document’s DOM, userscript developers have full control over the visual presentation of any site they visit.


How Userscripts Handle CSS Injection

While userscripts are primarily written in JavaScript to modify webpage behavior, styling is often a core component of web customization. Developers typically use two primary approaches to inject CSS via a userscript.

1. Using Extension APIs (GM_addStyle)

Most popular userscript managers—such as Tampermonkey, Violentmonkey, and Greasemonkey—provide built-in helper functions designed specifically for CSS injection. The most common tool is GM_addStyle.

To use this method, the script must request permission in its metadata block:

// ==UserScript==
// @name         Custom CSS Injector
// @namespace    http://tampermonkey.net/
// @version      1.0
// @match        https://example.com/*
// @grant        GM_addStyle
// ==UserScript==

GM_addStyle(`
    body {
        background-color: #121212 !important;
        color: #ffffff !important;
    }
    .ad-banner {
        display: none !important;
    }
`);

Key Advantages:


2. Native DOM Manipulation

If a userscript needs to run without special grants or browser extension APIs, it can inject styles using standard JavaScript DOM APIs.

This is done by creating a <style> element, setting its text content to the desired CSS, and appending it to the document’s <head> or <body>.

// ==UserScript==
// @name         Native CSS Injector
// @namespace    http://tampermonkey.net/
// @version      1.0
// @match        https://example.com/*
// @grant        none
// ==UserScript==

(function() {
    'use strict';

    const css = `
        body {
            font-family: Arial, sans-serif;
        }
    `;

    const style = document.createElement('style');
    style.type = 'text/css';
    style.textContent = css;

    (document.head || document.documentElement).appendChild(style);
})();

Common Use Cases for Custom CSS Injection


Best Practices and Considerations