Scriptlet rules
This document describes the syntax for the scriptlet rules Zen supports, and the scriptlets they can run. A scriptlet is a predefined script that changes how the page’s own scripts behave: for example, it can stop a script from reading a property, or block a fetch() request.
Top-level syntax
A rule consists of a domain list (optional), a marker, and, in parentheses, the name of the scriptlet followed by its arguments. A rule may be written in two equivalent forms, with the markers ##+js and #%#//scriptlet:
<domain-list>##+js(<name>, <arg1>, <arg2>, ...)
<domain-list>#%#//scriptlet('<name>', '<arg1>', '<arg2>', ...)
! for example:
example.com##+js(set-constant, ads.enabled, false)
example.com#%#//scriptlet('set-constant', 'ads.enabled', 'false')In the ##+js form:
- Arguments are separated by
,. Spaces around each argument are removed. - To include a
,in an argument, write\,. - An argument may be wrapped in
',", or`. The quotes are not part of the argument. Inside them,,needs no escaping, and the quote character is escaped with\.
In the #%#//scriptlet form:
- The name and each argument must be wrapped in
'or", and all of them must use the same quote character. - Arguments are separated by
,. Spaces around,are ignored. - The quote character is escaped with
\.
In both forms, a backslash that does not escape , or a quote character is kept: /ad\d+/ reaches the scriptlet unchanged.
To skip an optional argument and give a later one, leave it empty: set-constant, ads, true, , asFunction.
If no scriptlet has the given name, the rule has no effect. Names are case-sensitive.
Rules for scriptlets whose names start with trusted- apply only from trusted filter lists.
Argument formats
Several scriptlets take arguments in the formats below.
Search patterns
A search pattern is either a regular expression literal or a plain string. A regular expression literal has the form /pattern/ or /pattern/flags, where the pattern contains no unescaped /: /ad\d+/, /sponsored/i. It is read as a JavaScript regular expression. A plain string is matched as a case-sensitive substring: ad matches load. An empty search pattern matches everything.
Property chains
A property chain is a path to a property, starting from window, with the parts separated by .: ads.config.enabled stands for window.ads.config.enabled. The parts of the chain may be created by the page after the scriptlet runs.
Request properties
A request properties argument selects network requests. It is a list of conditions separated by spaces, and a request must meet all of them. Each condition is either:
- A search pattern for the request URL:
ads.jsor/ads\d/. name:value, wherevalueis a regular expression literal or a string that must match in full:method:POST.nameis one ofurl,method,credentials,cache,redirect,referrer,referrerPolicy,integrity, ormode, the names of theRequestproperties.
Neither a URL pattern nor a value may contain :.
If several URL conditions are given, only the last one is used.
An empty argument or * selects every request. For fetch() requests, a condition on a property that the call does not set never matches: method:GET does not match fetch('/ads'). For XMLHttpRequest requests, a condition on any property other than url or method never matches.
JSON paths
A JSON paths argument is a list of paths separated by spaces. Each path is a list of property names separated by .: ads.banner. Two parts have a special meaning:
[]stands for every element of an array:items.[].ad.*stands for one or more nested properties:*.admatchesa.adanda.b.ad, but notad.
Exception rules
An exception rule cancels scriptlet rules on the pages it applies to. It uses the marker #@#+js or #@%#//scriptlet:
##+js(prevent-setTimeout, ads)
example.com#@#+js(prevent-setTimeout, ads)Here, the first rule applies on every domain, and the second one cancels it on example.com and its subdomains.
An exception rule cancels a rule only if both have the same name and the same arguments. The form, quotes, and spaces around arguments do not matter: example.com#@#+js(set-constant, ads, false) cancels example.com#%#//scriptlet('set-constant', 'ads', 'false'). The names listed under “May also be written as” count as different names: an exception for set does not cancel a rule for set-constant.
A generic exception rule cancels matching rules on every domain.
Page injection
Scriptlets are inserted into pages right before the first </head> tag. Scripts that appear earlier in the page run before them. A page without a </head> tag gets no scriptlets.
Each scriptlet rule runs separately: if one fails, the others still run.
Most scriptlet messages in the browser console start with Zen (, usually followed by the name of the scriptlet.
Scriptlets
abort-current-inline-script
Throws a ReferenceError when a script reads or writes a property while its <script> element is running, which stops the script unless it catches the error. Code that the script runs later, such as timer callbacks, is not affected.
Arguments:
property: a property chain.search(optional): a search pattern matched against the text of the script. Without it, every script that reads or writes the property is stopped, including external scripts.
abort-on-property-read
Throws a ReferenceError when a script reads a property. May also be written as aopr.
Arguments:
property: a property chain.
abort-on-property-write
Throws a ReferenceError when a script writes a property. May also be written as aopw.
Arguments:
property: a property chain.
abort-on-stack-trace
Throws a ReferenceError when a script reads or writes a property and a line of the call stack matches a pattern. May also be written as aost.
Arguments:
property: a property chain.stack: a non-empty search pattern matched against each line of the call stack.
json-prune
Removes properties from the objects returned by JSON.parse() and Response.json().
Arguments:
propsToRemove: JSON paths to remove.requiredProps(optional): JSON paths. If given, properties are removed only from objects that contain at least one of these paths.stack(optional): a search pattern. If given, properties are removed only when a line of the call stack matches it.
json-prune-fetch-response
Removes properties from the JSON responses to matching fetch() requests.
Arguments:
propsToRemove: JSON paths to remove.requiredProps(optional): as injson-prune.propsToMatch(optional): request properties.stack(optional): as injson-prune.
json-prune-xhr-response
Removes properties from the JSON responses to matching XMLHttpRequest requests. Takes the same arguments as json-prune-fetch-response.
no-protected-audience
Disables the Protected Audience API: its methods on navigator do nothing and return empty results. Takes no arguments.
no-topics
Disables the Topics API: document.browsingTopics() returns no topics. Takes no arguments.
nowebrtc
Disables WebRTC by replacing RTCPeerConnection, so that pages cannot create peer connections. Takes no arguments.
prevent-addEventListener
Prevents matching event listeners from being added with addEventListener().
Arguments:
event(optional): a search pattern matched against the event type.search(optional): a search pattern matched against the source code of the listener.
A listener is prevented if both arguments match. An omitted argument matches every listener. With neither argument, the scriptlet has no effect.
prevent-fetch
Blocks matching fetch() requests. The fetch() call resolves to a fake response with the status 200 instead. May also be written as no-fetch-if.
Arguments:
propsToMatch: request properties.responseBody(optional): the body of the fake response. One ofemptyObj({}, the default),emptyArr([]), oremptyStr(an empty body).responseType(optional): the type of the fake response. One ofbasic(the default),cors, oropaque. Anopaqueresponse has the status0and no body.
prevent-setTimeout and prevent-setInterval
Prevent matching calls to setTimeout() and setInterval(). A prevented call never runs its callback.
Arguments:
search(optional): a search pattern matched against the source code of the callback.delay(optional): an integer that must equal the delay of the call, in milliseconds.
Either argument may start with ! to prevent the calls that do not match it instead. An empty argument is ignored. With no arguments, every call is prevented.
prevent-window-open
Prevents matching calls to window.open(). May also be written as nowoif.
By default, a prevented call loads the URL in a hidden iframe instead of opening a window, and returns a fake window object.
Arguments:
match(optional): a search pattern matched against the URL. It may start with!to prevent the calls that do not match it instead. Without it, every call is prevented.delay(optional): removes the iframe after this many seconds.replacement(optional):objloads the URL in an<object>element instead of an iframe.blankopens a window withabout:blankinstead of the URL.
If the first argument is 1 or 0, the arguments are read differently, and a prevented call does not load the URL:
match:1prevents the calls whose URL matchessearch, and0the calls whose URL does not.search(optional): a search pattern matched against the URL. Without it, every call is prevented.replacement(optional): what the prevented call returns.trueFuncreturns a function that returnstrue.{name=noopFunc}returns an object with a methodnamethat does nothing. Without it, the call returns a function that does nothing.
prevent-xhr
Blocks matching XMLHttpRequest requests. The request completes with the status 200 and an empty response instead. May also be written as no-xhr-if.
Arguments:
propsToMatch: request properties.randomize(optional): replaces the empty response text with random characters.truegives 10 characters, andlength:N-Mgives betweenNandMcharacters, whereMis at most 500000. Applies only to text responses.
sanitize-clipboard
Removes query parameters from the URLs that the page copies to the clipboard.
Arguments:
params: a list of parameter names separated by spaces. Each name must match in full, or be a regular expression literal:utm_source /^utm_/.
set-constant
Makes a property always return a fixed value. The page may still assign to the property, but reading it returns the fixed value. May also be written as set or ubo-set.
Arguments:
property: a property chain.value: one of the following:undefined,false,true, ornull.emptyObjor{}: an empty object.emptyArror[]: an empty array.noopFunc: a function that does nothing.noopCallbackFunc: a function that returns a function that does nothing.trueFuncandfalseFunc: functions that returntrueandfalse.throwFunc: a function that throws an error.noopPromiseResolveandnoopPromiseReject: functions that return a promise resolved with an emptyResponse, and a rejected promise.''(an empty string),yes, orno.- An integer from -32767 to 32767.
If the argument after value is not as or runAt, the remaining arguments are positional:
stack(optional): a search pattern. If given, the value is returned only when a line of the call stack matches it.valueWrapper(optional):asFunction: the property becomes a function that returns the value.asCallback: a function that returns such a function.asResolvedandasRejected: a promise resolved or rejected with the value.
Otherwise, the remaining arguments are pairs of a name and a value, in any order:
as, <wrapper>: wraps the value likevalueWrapper, where<wrapper>isfunction,callback,resolved, orrejected.runAt, <state>: sets the property only once the page reaches a ready state.<state>isloading,interactive, orcomplete.
For example:
example.com##+js(set-constant, ads.isBlocked, noopFunc, as, function)set-cookie
Sets a cookie that lasts until the browser session ends. May also be written as ubo-set-cookie.
Arguments:
name: the name of the cookie. It must not contain;or=.value: one of the following:- A word from a fixed list of values that cookie consent banners use, such as
accept,reject,true, oroff. Case does not matter. - An integer from -32767 to 32767.
emptyObj({}) oremptyArr([]).
- A word from a fixed list of values that cookie consent banners use, such as
path(optional):/(the default) ornone, which sets the cookie without a path.
If the argument after path is not domain, reload, or dontOverwrite, it is the domain of the cookie. Otherwise, the remaining arguments are pairs of a name and a value, in any order:
domain, <domain>: the domain of the cookie.reload, 1: reloads the page after setting the cookie, asset-cookie-reloaddoes.dontOverwrite, 1: does not change a cookie that already exists.
set-cookie-reload
Like set-cookie, and then reloads the page if the cookie did not already have this value. It does not reload if the current page load is itself a reload. Takes the same arguments as set-cookie.
set-local-storage-item and set-session-storage-item
Set or remove an item in localStorage or sessionStorage.
Arguments:
key: the key of the item.value: one of the following:undefined,false,true,null,yes,no,on,off,accept,accepted,reject,rejected,allowed,denied,forbidden,forever, or''(an empty string). Case does not matter.emptyObj({}) oremptyArr([]).- An integer from 0 to 32767.
$remove$, which removes the item. In this case,keymay be a regular expression literal, which removes every item whose key matches it.
trusted-set-cookie
Like set-cookie, but accepts any value and an expiry time.
Arguments:
name: as inset-cookie.value: any string.$now$is replaced with the current time in milliseconds since the Unix epoch,$currentDate$with the current date and time, and$currentISODate$with the current date and time in ISO 8601 format.offsetExpiresSec(optional): when the cookie expires.1day,1year, or a number of seconds. Without it, the cookie lasts until the browser session ends.path(optional): as inset-cookie.
The arguments after path are the same as in set-cookie.
trusted-set-cookie-reload
Like trusted-set-cookie, and then reloads the page as set-cookie-reload does.