How Do You Specify Which Websites Userscripts Run On?

Userscripts customize your browsing experience by running custom JavaScript on targeted web pages, relying on specific metadata header rules to determine precisely where and when they execute. By using directives like @match, @include, and @exclude inside the script’s header block, developers can control script execution down to exact URLs, domain patterns, or global wildcards. Understanding how to properly format these rules ensures your userscripts run efficiently on intended sites without inadvertently causing issues or security risks on others.


The Metadata Block

Every userscript begins with a top metadata block—a collection of comments containing key-value pairs that popular browser extensions (such as Tampermonkey, Violentmonkey, or Greasemonkey) parse before running the script.

// ==UserScript==
// @name         My Custom Script
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  A brief description of what the script does
// @match        https://www.example.com/*
// ==/UserScript==

Within this block, pattern-matching directives tell the extension engine which pages qualify for script injection.


Primary Directives for URL Matching

The @match directive is the modern standard for defining URL patterns. It uses a strict, standardized syntax consisting of three main parts: <scheme>://<host><path>.

Common @match Examples


2. The @include Directive

The @include directive is an older, more permissive rule format. While @match follows strict structure guidelines to prevent syntax errors, @include allows flexible wildcards anywhere in the string or even full Regular Expressions.

Note: While @include offers high flexibility through regular expressions, major user script managers recommend @match for better performance and security consistency across browsers.


3. The @exclude Directive

The @exclude directive explicitly prevents a script from running on specified URLs, overriding any matching @match or @include rules. This is useful when you want a script to run across an entire domain except for a few specific pages, such as checkout or settings screens.

// ==UserScript==
// @name         Global Site Enhancer
// @match        https://example.com/*
// @exclude      https://example.com/login
// @exclude      https://example.com/cart/*
// ==/UserScript==

Matching Multiple Domains

If your userscript needs to run on several specific websites, declare multiple @match or @include lines inside the metadata block. The script manager evaluates all declarations and executes the script if any match condition is satisfied.

// ==UserScript==
// @name         Multi-Site Utility
// @match        https://*.github.com/*
// @match        https://*.gitlab.com/*
// @match        https://*.bitbucket.org/*
// ==/UserScript==