Run tampermonkey script only on one site

Summary

This incident involved a Tampermonkey userscript that was intended to run only on YouTube, but instead executed on every website. The root cause was an incorrect or overly broad @match pattern that unintentionally matched all domains.

Root Cause

The issue stemmed from the following pattern:

  • @match https://*.youtube.com/*

While it looks correct, the real problem is that Tampermonkey treats invalid or malformed match patterns as wildcards, causing the script to run everywhere.

Common causes include:

  • A missing protocol (http vs https)
  • A stray invisible character or whitespace
  • A malformed wildcard pattern
  • Using @include or @match incorrectly

Why This Happens in Real Systems

Real-world script engines behave defensively:

  • Invalid match patterns fail open, not closed
  • Browsers normalize URLs, sometimes making patterns match more than expected
  • Userscript managers differ slightly in pattern validation, leading to unexpected behavior
  • Copy‑pasted metadata blocks often contain hidden characters

Real-World Impact

When a userscript runs on unintended sites, it can cause:

  • Performance degradation on unrelated pages
  • JavaScript errors polluting console logs
  • Unexpected DOM manipulation breaking page layouts
  • Security concerns if the script interacts with sensitive pages

Example or Code (if necessary and relevant)

A correct, minimal YouTube-only match block:

// ==UserScript==
// @name YouTube Only Script
// @namespace https://greasyfork.org/
// @match https://www.youtube.com/*
// @match https://m.youtube.com/*
// @grant none
// @run-at document-start
// ==/UserScript==

How Senior Engineers Fix It

Experienced engineers typically:

  • Validate match patterns using Tampermonkey’s built‑in tester
  • Avoid overly broad wildcards
  • Specify exact subdomains instead of relying on *
  • Check for hidden characters by rewriting the metadata block manually
  • Use multiple explicit @match lines for clarity and safety

Why Juniors Miss It

Less experienced developers often overlook:

  • How strict the @match syntax actually is
  • That one malformed line can cause a global match
  • That copy‑pasted metadata may contain invisible Unicode characters
  • The difference between @include and @match behavior
  • The fact that Tampermonkey fails open, not closed

Juniors assume the pattern is correct because it looks correct, while seniors know to verify it explicitly.

Leave a Comment