Skip to content

JavaScript rules

This document describes the syntax for the JavaScript rules Zen supports. A JavaScript rule runs custom JavaScript code on matching pages.

JavaScript rules, including exception rules, apply only from trusted filter lists.

Top-level syntax

A rule consists of a domain list (optional), the marker #%#, and a body of JavaScript code:

<domain-list>#%#<body>
! for example:
example.com#%#window.adsEnabled = false;

The first # in a line always starts the marker, so the body may contain #.

A rule whose body starts with //scriptlet is a scriptlet rule, not a JavaScript rule.

Execution

The bodies of all rules that apply to a page are joined into one script and wrapped in a single function that runs at once. For example, these rules:

example.com#%#window.adsEnabled = false;
example.com#%#init()

become this script on example.com:

(function(){window.adsEnabled = false;init();})();

The order of the bodies in the script is not defined. Because the bodies share one script:

  • A syntax error in one body stops every JavaScript rule on the page from running. A // comment in a body has the same effect, because it comments out the rest of the script.
  • An uncaught exception or a top-level return in one body stops the bodies after it.
  • Names declared with var, let, const, function, or class are local to the function, so the page’s scripts cannot use them. Two bodies that declare the same name with let, const, or class cause a syntax error.

Page injection

The script is inserted into pages right before the first </head> tag, after the scriptlets, so scriptlets run first. Scripts that appear earlier in the page also run before it. When the script runs, the page’s <body> has not been parsed yet. A page without a </head> tag gets no JavaScript rules.

Exception rules

An exception rule cancels the JavaScript rules with exactly the same body, character for character, on the pages it applies to. It uses the marker #@%#:

#%#window.adsEnabled = false;
example.com#@%#window.adsEnabled = false;

Here, the first rule runs on every domain, and the second one cancels it on example.com and its subdomains.

A generic exception rule cancels matching rules on every domain.