What Does the @match Directive Do in Userscripts?
The @match directive in userscripts specifies the exact
web pages where a script is permitted to execute. By utilizing
standardized url match patterns, it gives developers precise control
over domain, protocol, and path targeting, ensuring that custom scripts
only run on intended websites rather than globally across the web.
How the @match
Directive Works
When you install a userscript in browser extensions like
Tampermonkey, Violentmonkey, or Greasemonkey, the extension inspects the
script’s metadata block before loading it. The @match rule
acts as a filter. If the URL of the current browser tab matches the
pattern defined in the directive, the userscript manager injects and
executes your code. If the URL does not match, the script remains
inactive.
A standard @match rule follows a strict format
consisting of three distinct parts:
// @match <scheme>://<host><path>
- Scheme: Defines the protocol, such as
http,https,file, or a wildcard*to cover bothhttpandhttps. - Host: Specifies the domain name (e.g.,
example.com). You can use a wildcard at the beginning to include subdomains (e.g.,*.example.com). - Path: Dictates the specific page path after the
domain (e.g.,
/searchor/*). The*character acts as a wildcard representing zero or more characters.
Common Examples of
@match Patterns
Developers use various pattern combinations depending on how broadly or narrowly they want their script to apply:
// @match https://www.example.com/*— Runs on every page underhttps://www.example.com/.// @match *://*.example.com/*— Runs onexample.comand all of its subdomains across both HTTP and HTTPS.// @match https://example.com/docs/*.html— Runs only on HTTPS pages in the/docs/directory that end with.html.// @match *://*/*— Runs on every website (use with caution, as global scripts can slow down browsing or cause unexpected side effects).
Multiple @match lines can be added to the metadata block
if a single script needs to target several distinct domain patterns.
@match
vs. @include
While both directives define target URLs, modern userscript
development heavily favors @match over the older
@include directive:
- Security and Standardization:
@matchfollows the strict Chrome Extension match pattern rules, preventing overly permissive or malformed syntax. - Performance: Userscript managers can parse
@matchrules significantly faster because they do not allow arbitrary regular expressions, unlike@include. - Predictability: The restricted syntax of
@matchensures that patterns behave consistently across different userscript managers and browser engines.