Skip to content
This repository has been archived by the owner on Feb 6, 2023. It is now read-only.

Update description of the $domain modifier #1109

Merged
merged 7 commits into from
Sep 12, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 33 additions & 18 deletions 01.general/02.how-to-create-your-own-ad-filters/docs.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ visible: true
* [Basic rules syntax](#basic-rules-syntax)
* [Special characters](#basic-rules-special-characters)
* [Regular expressions support](#regexp-support)
* [Wildcard support for TLD](#wildcard-for-tld)
* [Basic rules examples](#basic-rules-examples)
* [Modifiers](#basic-rules-modifiers)
* [Basic modifiers](#basic-rules-common-modifiers)
Expand Down Expand Up @@ -74,6 +73,7 @@ visible: true
* [$empty (deprecated)](#empty-modifier)
* [$mp4 (deprecated)](#mp4-modifier)
* [Non-basic rules](#non-basic-rules)
* [Wildcard support for TLD](#wildcard-for-tld)
sxgunchenko marked this conversation as resolved.
Show resolved Hide resolved
* [Cosmetic rules](#cosmetic-rules)
* [Element hiding rules](#cosmetic-elemhide-rules)
* [CSS rules](#cosmetic-css-rules)
Expand Down Expand Up @@ -292,15 +292,6 @@ For example, `/banner\d+/$third-party` this rule will apply the regular expressi

> **Compatibility with different versions of AdGuard.** AdGuard Safari and AdGuard for iOS do not fully support regular expressions because of [Content Blocking API restrictions](https://webkit.org/blog/3476/content-blockers-first-look/) (look for "The Regular expression format" section).

<a id="wildcard-for-tld"></a>
### Wildcard support for TLD (top-level domains)

Wildcard characters are supported for TLDs of the domains in patterns of cosmetic, html and javascript rules.
For example, the cosmetic rule `example.*##.banner` will match any `example.TLD` request (`example.ru`, `example.com`, `example.net`, `example.org`, etc.).
For the basic rules the described logic will be applicable only for the domains specified in `$domain` modifier (for example, `||*/banners/*$image,domain=example.*`).

> **Compatibility with different versions of AdGuard.** Rules with wildcard for TLD are supported by AdGuard for Windows, Mac, Android, Safari, iOS, and AdGuard Browser extension for Chrome, Firefox, Edge.

<a id="basic-rules-examples"></a>
### Basic rules examples

Expand Down Expand Up @@ -330,19 +321,33 @@ The following modifiers are the most simple and frequently used.
<a id="domain-modifier"></a>
##### **`domain`**

`domain` limits the rule application area to a list of domains (and their subdomains). To add multiple domains to one rule, use the `|` character as a separator.
`domain` limits the rule application area to a list of domains (and their subdomains).

###### `domain` examples
###### Syntax

* `||baddomain.com^$domain=example.org` — a rule to block requests that match the specified mask, and are sent from domain `example.org` or its subdomains.
* `||baddomain.com^$domain=example.org|example.com` — the same rule, but it works for both `example.org` and `example.com`.
The modifier is a list of one or more expressions separated by `|` symbol, each of which is matched against a domain in a certain way depending on its type (see below).

```
domains = ["~"] entry_0 ["|" ["~"] entry_1 ["|" ["~"]entry_2 ["|" ... ["|" ["~"]entry_N]]]]
entry_i = ( regular_domain / any_tld_domain / regex )
```

* **`regular_domain`** — a regular domain name (`domain.com`). Corresponds the specified domain and its subdomains. It is matched lexicographically.
* **`any_tld_domain`** — a domain name ending with wildcard character as TLD (`domain.*`). Corresponds to the specified domain and its subdomains with any TLD. It is matched lexicographically.
* **`regex`** — a regular expression, starts and ends with `/`. The pattern works the same way as in the basic URL rules, but the characters `/`, `$`, and `|` must be escaped with `\`.

If you want the rule not to be applied to certain domains, start a domain name with `~` sign.
> **Compatibility with different versions of AdGuard.** Rules with regular expressions in the `$domain` modifier are supported by AdGuard for Windows, Mac, and Android, **running CoreLibs version 1.10 or later**.

###### `domain` and `~` examples
The `~` symbol before an expression is used to indicate exceptions. Queries from domains matching such expressions are not affected by rules containing them.

**Examples:**

* `||baddomain.com^$domain=example.org` — a rule to block requests that match the specified mask, and are sent from domain `example.org` or its subdomains.
* `||baddomain.com^$domain=example.org|example.com` — the same rule, but it works for both `example.org` and `example.com`.
* `||baddomain.com^$domain=~example.org` — this rule blocks requests matching the pattern sent from any domain except `example.org` and its subdomains.
* `||baddomain.com^$domain=example.org|~foo.example.org` — this rule blocks requests sent from `example.org` and its subdomains, except the subdomain `foo.example.org`.
* `||baddomain.com^$domain=/(^\|.+\.)example\.(com\|org)\$/` - this rule will blocks requests sent from `example.org` and `example.com` domains and all their subdomains.
* `||baddomain.com^$domain=~a.com|~b.*|~/(^\|.+\.)c\.(com\|org)\$/` - this rule will blocks requests sent from any domains except `a.com`, `b` with any TLD (`b.com`, `b.co.uk`, etc.), `c.com` and `c.org`, as well as all subdomains of all the specified domains.

###### `domain` modifier matching target domain

Expand Down Expand Up @@ -1421,6 +1426,15 @@ As a response to blocked request AdGuard returns a short video placeholder.

However, the capabilities of the basic rules may not be sufficient to block ads. Sometimes you need to hide an element or change part of the HTML code of a web page without breaking anything. The rules described in this section are created specifically for this purpose.

<a id="wildcard-for-tld"></a>
## Wildcard support for TLD (top-level domains)

Wildcard characters are supported for TLDs of the domains in patterns of cosmetic, html and javascript rules.
For example, the cosmetic rule `example.*##.banner` will match any `example.TLD` request (`example.ru`, `example.com`, `example.net`, `example.org`, etc.).
For the basic rules the described logic will be applicable only for the domains specified in `$domain` modifier (for example, `||*/banners/*$image,domain=example.*`).

> **Compatibility with different versions of AdGuard.** Rules with wildcard for TLD are supported by AdGuard for Windows, Mac, Android, Safari, iOS, and AdGuard Browser extension for Chrome, Firefox, Edge.

<a id="cosmetic-rules"></a>
## Cosmetic rules

Expand Down Expand Up @@ -2210,13 +2224,14 @@ The modifier's behavior and syntax perfectly match the corresponding [basic rule
### `domain`

`$domain` modifier limits the rule application area to a list of domains and their subdomains.
The modifier's behavior and syntax perfectly match the corresponding
[basic rules `$domain` modifier](#domain-modifier).
The modifier's behavior and syntax are almost exactly the same as the corresponding [basic rules `$domain` modifier](#domain-modifier).
The only difference is that the `|` domain separator in regular expressions does not need to be escaped.

#### `domain` examples:
* `[$domain=example.com]##.textad` — hides a `div` with a class `textad` at `example.com` and all subdomains.
* `[$domain=example.com|example.org]###adblock` — hides an element with attribute `id` equals `adblock` at `example.com`, `example.org` and all subdomains.
* `[$domain=~example.com]##.textad` — this rule hides `div` elements of the class `textad` for all domains, except `example.com` and its subdomains.
* `[$domain=/(^|.+\.)example\.(com|org)\$/]##.textad` — hides a `div` with a class `textad` at `example.com`, `example.org` and all subdomains.

Please note that there are 2 ways to specify domain restrictions for non-basic rules:
1) the "classic" way is to specify domains before rule mask and attributes: `example.com##.textad`
Expand Down
49 changes: 33 additions & 16 deletions 01.general/02.how-to-create-your-own-ad-filters/docs.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ visible: true
* [Синтаксис базовых правил](#basic-rules-syntax)
* [Специальные символы](#basic-rules-special-characters)
* [Поддержка регулярных выражений](#regexp-support)
* [Поддержка wildcard для TLD](#wildcard-for-tld)
* [Примеры базовых правил](#basic-rules-examples)
* [Модификаторы](#basic-rules-modifiers)
* [Базовые модификаторы](#basic-rules-common-modifiers)
Expand Down Expand Up @@ -74,6 +73,7 @@ visible: true
* [$empty (устаревший)](#empty-modifier)
* [$mp4 (устаревший)](#mp4-modifier)
* [Другие правила](#non-basic-rules)
* [Поддержка wildcard для TLD](#wildcard-for-tld)
* [Косметические правила](#cosmetic-rules)
* [Правила скрытия элементов](#cosmetic-elemhide-rules)
* [Правила CSS-стилей](#cosmetic-css-rules)
Expand Down Expand Up @@ -292,14 +292,6 @@ pattern = "/" regexp "/"

> **Совместимость с разными версиями AdGuard.** AdGuard для Safari и AdGuard для iOS не полностью поддерживают регулярные выражения в силу [ограничений Content Blocking API](https://webkit.org/blog/3476/content-blockers-first-look/) (в статье по ссылке найдите раздел "The Regular expression format").

<a id="wildcard-for-tld"></a>
### Поддержка wildcard для доменов верхнего уровня (TLD)

Вы можете использовать wildcard-символ для доменов верхнего уровня в паттернах косметических, html и js правил. Например, правило `example.*##.banner` будет соответствовать всем `example.TLD` доменам: `example.ru`, `example.com`, `example.net`, `example.org` и т.д.
При составлении базовых правил вы можете использовать *wildcard-символ для TLD* только вместе с модификатором `$domain`. Например, `||*/banners/*$image,domain=example.*`

> **Совместимость с разными версиями AdGuard.** Правила с wildcard для TLD поддерживается в AdGuard для Windows, Mac, Android, Safari, iOS и в Браузерном расширении AdGuard для Chrome, Firefox, Edge.

<a id="basic-rules-examples"></a>
### Примеры базовых правил

Expand Down Expand Up @@ -331,19 +323,34 @@ pattern = "/" regexp "/"
<a id="domain-modifier"></a>
##### **`domain`**

Модификатор `domain` ограничивает область действия правила списком доменов (и их поддоменов). Для того чтобы указать несколько доменов в одном правиле, нужно использовать символ `|` в качестве разделителя.
Модификатор `domain` ограничивает область действия правила списком доменов (и их поддоменов).

###### Примеры `domain`
###### Синтаксис

* `||baddomain.com^$domain=example.org` — правило для блокировки запросов, которые соответствуют указанной маске, и отправленных с домена или поддомена `example.org`.
* `||baddomain.com^$domain=example.org|example.com` — такое же правило, но срабатывать оно будет как для домена `example.org`, так и для `example.com`.
Модификатор представляет собой список из одного или нескольких выражений, разделённых символом `|`, каждое из которых сопоставляется с доменом определённым образом в зависимости от типа (см. ниже).

```
domains = ["~"] entry_0 ["|" ["~"] entry_1 ["|" ["~"]entry_2 ["|" ... ["|" ["~"]entry_N]]]]
entry_i = ( regular_domain / any_tld_domain / regex )
```

* **`regular_domain`** — обычное имя домена (`domain.com`). Соответствует указанному домену и его поддоменам. Сопоставляется лексикографически.
* **`any_tld_domain`** — имя домена, оканчивающееся wildcard-символом в качестве TLD (`domain.*`). Соответствует указанному домену и его поддоменам с любым TLD. Сопоставляется лексикографически.
* **`regex`** — регулярное выражение, начинается и заканчивается символами `/`. Паттерн работает так же, как в базовых URL правилах, однако символы `/`, `$`, и `|` необходимо экранировать с помощью `\`.

Чтобы правило не применялось на определенных доменах, перед доменным именем необходимо добавить символ `~`.
> **Совместимость с разными версиями AdGuard.** Правила с регулярными выражениями в модификаторе `$domain` поддерживаются в AdGuard для Windows, Mac, и Android, **с CoreLibs версии 1.11 или выше**.

###### Примеры `domain` и `~`
Символ `~` перед выражением используется для обозначения исключений. Запросы с доменов, соответствующих таким выражениям, не попадают под действие правил, содержащих их.

**Примеры:**

* `||baddomain.com^$domain=example.org` — правило для блокировки запросов, которые соответствуют указанной маске, и отправленных с домена или поддомена `example.org`.
* `||baddomain.com^$domain=example.org|example.com` — такое же правило, но срабатывать оно будет как для домена `example.org`, так и для `example.com`.
* `||baddomain.com^$domain=example.*` — такое же правило, но срабатывать оно будет как для домена `example` с любым TLD: `example.org`, `example.com`, `example.co.uk` и т.д.
* `||baddomain.com^$domain=~example.org` — правило для блокировки запросов, которые соответствуют указанной маске, и отправленных с любого домена, кроме `example.org` и его поддоменов.
* `||baddomain.com^$domain=example.org|~foo.example.org` — в данном примере правило будет соответствовать запросам, отправленным с домена `example.org` и всех его поддоменов, кроме поддомена `foo.example.org`.
* `||baddomain.com^$domain=/(^\|.+\.)example\.(com\|org)\$/` — в данном примере правило будет соответствовать запросам, отправленным с доменов `example.org` и `example.com` и всех их поддоменов.
* `||baddomain.com^$domain=~a.com|~b.*|~/(^\|.+\.)c\.(com\|org)\$/` — в данном примере правило будет соответствовать запросам, отправленным с любых доменов, кроме `a.com`, `b` с любым TLD (`b.com`, `b.co.uk` и т.д.), `c.com` и `c.org`, а также всех поддоменов, всех указанных доменов.

###### Когда `domain` соответствует целевому домену

Expand Down Expand Up @@ -1408,6 +1415,14 @@ https://jsonpath.com/

Однако возможностей базовых правил может быть недостаточно, чтобы заблокировать рекламу. Иногда для этого требуется скрыть какой-нибудь элемент или изменить часть HTML-кода страницы, при этом ничего не сломав. Для этого предназначены правила, описанные в этом разделе.

<a id="wildcard-for-tld"></a>
## Поддержка wildcard для доменов верхнего уровня (TLD)

Вы можете использовать wildcard-символ для доменов верхнего уровня в паттернах косметических, html и js правил. Например, правило `example.*##.banner` будет соответствовать всем `example.TLD` доменам: `example.ru`, `example.com`, `example.net`, `example.org` и т.д.
При составлении базовых правил вы можете использовать *wildcard-символ для TLD* только вместе с модификатором `$domain`. Например, `||*/banners/*$image,domain=example.*`

> **Совместимость с разными версиями AdGuard.** Правила с wildcard для TLD поддерживается в AdGuard для Windows, Mac, Android, Safari, iOS и в Браузерном расширении AdGuard для Chrome, Firefox, Edge.

<a id="cosmetic-rules"></a>
## Косметические правила

Expand Down Expand Up @@ -2191,12 +2206,14 @@ modifiers = modifier0[, modifier1[, ...[, modifierN]]]
### `domain`

Модификатор `$domain` ограничивает область действия правила списком доменов и их поддоменов.
Поведение и синтаксис модификатора полностью совпадают с соответствующим [модификатором `$domain` для базовых правил](#domain-modifier).
Поведение и синтаксис модификатора почти полностью совпадают с соответствующим [модификатором `$domain` для базовых правил](#domain-modifier).
Единственное отличие в том, что разделитель доменов `|` в регулярных выражениях экранировать не требуется.

#### Примеры `domain`:
* `[$domain=example.com]##.textad` — скрывает `div` и заменяет его на класс `textad` на `example.com` и всех поддоменах.
* `[$domain=example.com|example.org]###adblock` — скрывает элемент с атрибутом `id`, равным `adblock`, на `example.com`, `example.org` и всех поддоменах.
* `[$domain=~example.com]##.textad` — скрывает `div` и заменяет его на класс `textad` на всех доменах кроме `example.com` и его поддоменов.
* `[$domain=/(^|.+\.)example\.(com|org)\$/]##.textad` — скрывает элемент с атрибутом `id`, равным `adblock`, на `example.com`, `example.org` и всех поддоменах.

Существует 2 способа указать доменные ограничения для косметических правил:
1) «классический»: обозначить ограничение на домены перед маской и атрибутами правила: `example.com##.textad`;
Expand Down