improve 'how to make user rules' article

This commit is contained in:
Slava 2022-05-27 19:27:53 +03:00 committed by GitHub
commit 7b7b82a625
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 227 additions and 219 deletions

View File

@ -296,7 +296,7 @@ Wildcard characters are supported for TLDs of the domains in patterns of cosmeti
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.** Supported by: AdGuard for Windows/macOS/Android/Safari/iOS and browser extensions for Chrome/Firefox/Edge.
> **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
@ -352,9 +352,9 @@ In some cases the `$domain` modifier can match not only the referrer domain, but
The following predicate should be satisfied to perform a target domain matching: `1 AND ((2 AND 3) OR 4)`. That is, if the modifier `$domain` contains only excluded domains, then the rule does not need to meet the second and third conditions to match the target domain against the modifier `$domain`.
If some of the conditions above aren't met but the rule contains modifiers `cookie` or `csp`, the target domain will still be matched.
If some of the conditions above aren't met but the rule contains [`$cookie`](#cookie-modifier) or [`$csp`](#csp-modifier) modifier, the target domain will still be matched.
If the referrer matches a rule with `domain` that explicitly excludes the referrer domain, then the rule won't be applied even if the target domain also matches the rule. This affects rules with `cookie` and `csp` modifiers, too.
If the referrer matches a rule with `$domain` that explicitly excludes the referrer domain, then the rule won't be applied even if the target domain also matches the rule. This affects rules with [`$cookie`](#cookie-modifier) and [`$csp`](#csp-modifier) modifiers, too.
**Examples:**
@ -370,7 +370,7 @@ In the following examples it's implied that requests are sent from `http://examp
* `/banner\d+/$domain=targetdomain.com` will not be matched as it contains a regular expression.
* `page$domain=targetdomain.com|~example.org` will not be matched because the referrer domain is explicitly excluded.
> **Important!** Safari doesn't support the simultaneous use of allowed and disallowed domains, so rules like `||baddomain.com^$domain=example.org|~foo.example.org` will not work in AdGuard for Safari.
> **Limitations:** Safari doesn't support the simultaneous use of allowed and disallowed domains, so rules like `||baddomain.com^$domain=example.org|~foo.example.org` will not work in AdGuard for Safari.
<a id="third-party-modifier"></a>
@ -405,7 +405,7 @@ AdGuard will try to close the browser tab with any address that matches a blocki
> It may not work if the popped up page is cached by the browser. It also will not work with some tricky popup methods. In such cases, it is better to use [AdGuard Popup Blocker](https://github.com/AdguardTeam/PopupBlocker) extension.
> **Important!** Unlike with browser extensions, `$popup` modifier is very unreliable when used with AdGuard apps for Windows, Mac and Android. In AdGuard for Safari and iOS, `$popup` rules will simply block the page right away.
> **Please note:** Unlike with browser extensions, `$popup` modifier is very unreliable when used with AdGuard apps for Windows, Mac and Android. In AdGuard for Safari and iOS, `$popup` rules will simply block the page right away.
<a id="match-case-modifier"></a>
##### **`match-case`**
@ -421,7 +421,7 @@ This modifier defines a rule which applies only to addresses that match the case
There is a set of modifiers, which can be used to limit the rule's application area to certain type of content. These modifiers can also be combined to cover, for example, both images and scripts.
> **Compatibility with different versions of AdGuard.** Please note that there is a big difference in how AdGuard determines the content type on different platforms. For browser extensions, content type for every request is provided by browser. AdGuard for Windows, Mac and Android use following method: first we try to determine the type of the request by the `Sec-Fetch-Dest` request header or by the filename extension. If the request is not blocked at this stage, the type will be determined using the `Content-Type` header at the beginning of the server response.
> **Compatibility with different versions of AdGuard.** There is a big difference in how AdGuard determines the content type on different platforms. For browser extensions, content type for every request is provided by browser. AdGuard for Windows, Mac, Android use following method: first we try to determine the type of the request by the `Sec-Fetch-Dest` request header or by the filename extension. If the request is not blocked at this stage, the type will be determined using the `Content-Type` header at the beginning of the server response.
<a id="content-type-modifiers-examples"></a>
##### Content type modifiers examples
@ -439,8 +439,6 @@ By default, AdGuard won't block the requests that are loaded in the browser tab
If this modifier is used with an exclusion rule (`@@`), it completely disables blocking on corresponding pages. It is equivalent to using `$elemhide`, `$content`, `$urlblock`, `$jsinject`, and `$extension` modifiers simultaneously.
> **Compatibility with different versions of AdGuard.** Blocking request type logic now only supported by dev-build of AdGuard.
###### `document` example
* `@@||example.com^$document` — completely disables filtering on all pages at `example.com` and all subdomains.
@ -451,6 +449,8 @@ If this modifier is used with an exclusion rule (`@@`), it completely disables b
* `||example.com^$document,removeparam=test` — removes `test` query parameter from HTML document request to `example.com`.
* `||example.com^$document,replace=/test1/test2/` — replaces `test1` with `test2` in HTML document request to `example.com`.
> **Compatibility with different versions of AdGuard.** Blocking rules with `$document` modifier are not supported by AdGuard Content Blocker.
<a id="image-modifier"></a>
##### **`image`**
@ -464,19 +464,19 @@ The rule corresponds to CSS files requests.
<a id="script-modifier"></a>
##### **`script`**
The rule corresponds to script requests (e.g. javascript, vbscript).
The rule corresponds to script requests, e.g. javascript, vbscript.
<a id="object-modifier"></a>
##### **`object`**
The rule corresponds to browser plugins resources. (e.g. Java or Flash).
The rule corresponds to browser plugins resources, e.g. Java or Flash.
<a id="object-subrequest-modifier"></a>
##### **`object-subrequest`**
The rule corresponds to requests by browser plugins (it's usually Flash).
> **Deprecation notice.** `object-subrequest` modifier is deprecated and no longer supported. Rules with it are considered as invalid.
> **Compatibility with different versions of AdGuard.** AdGuard for Windows, macOS and Android often can't accurately detect this type and defines it as `other`.
The rule corresponds to requests by browser plugins (it's usually Flash).
<a id="font-modifier"></a>
##### **`font`**
@ -486,37 +486,39 @@ The rule corresponds to requests for fonts (e.g. .woff filename extension).
<a id="media-modifier"></a>
##### **`media`**
The rule corresponds to requests for media files (music and video, e.g. .mp4 files).
The rule corresponds to requests for media files — music and video, e.g. .mp4 files.
<a id="subdocument-modifier"></a>
##### **`subdocument`**
The rule corresponds to requests for built-in pages (HTML tags `frame` and `iframe`).
The rule corresponds to requests for built-in pages — HTML tags `frame` and `iframe`.
<a id="ping-modifier"></a>
##### **`ping`**
The rule corresponds to requests caused by either `navigator.sendBeacon()` or the `ping` attribute on links.
> **Compatibility with different versions of AdGuard.** AdGuard for Windows, macOS and Android often can't accurately detect `navigator.sendBeacon()`. For reliable detection, use AdGuard browser extensions.
> **Compatibility with different versions of AdGuard.** AdGuard for Windows, Mac, Android often can't accurately detect `navigator.sendBeacon()`. For reliable detection, use AdGuard browser extensions.
<a id="xmlhttprequest-modifier"></a>
##### **`xmlhttprequest`**
The rule applies only to ajax requests (requests sent via javascript object `XMLHttpRequest`).
> **Compatibility with different versions of AdGuard.** AdGuard for Windows, macOS and Android often can't accurately detect this type and sometimes detects it as `other` or `script`.
> **Compatibility with different versions of AdGuard.** AdGuard for Windows, Mac, Android often can't accurately detect this type and sometimes detects it as [`$other`](#other-modifier) or [`$script`](#script-modifier). For reliable detection, use AdGuard browser extensions.
<a id="websocket-modifier"></a>
##### **`websocket`**
The rule applies only to WebSocket connections.
> **Compatibility with different versions of AdGuard.** AdGuard for Safari and iOS cannot properly apply this modifier due to Safari limitations.
> **Compatibility with different versions of AdGuard.** AdGuard for Safari and iOS cannot properly apply rules with `websocket` modifier due to Safari limitations.
<a id="webrtc-modifier"></a>
##### **`webrtc`**
> **Deprecation notice.** This modifier is deprecated and will be removed in the future. If you need to suppress WebRTC, consider using the `nowebrtc` [scriptlet](#scriptlets).
The rule applies only to WebRTC connections.
> Please note that blocking WebRTC can interfere with the work of some browser applications, such as messengers, chats, cinemas, or games.
@ -526,7 +528,7 @@ The rule applies only to WebRTC connections.
* `||example.com^$webrtc,domain=example.org` — this rule blocks webRTC connections to `example.com` for `example.org`.
* `@@*$webrtc,domain=example.org` — this rule disables the RTC wrapper for `example.org`.
> **Deprecation notice.** This modifier is deprecated and will be removed in the future. If you need to suppress WebRTC, consider using the `$nowebrtc` scriptlet.
> **Compatibility with different versions of AdGuard.** Rules with `webrtc` modifier are still supported by AdGuard browser extension.
<a id="other-modifier"></a>
##### **`other`**
@ -579,12 +581,14 @@ Disables blocking of all requests sent from the pages matching the rule.
<a id="extension-modifier"></a>
##### **`extension`**
Disables all userscripts on the pages matching this rule. Note, that this modifier only makes sense in AdGuard products that can work as userscript hosts (AdGuard for Windows/macOS/Android).
Disables all userscripts on the pages matching this rule.
###### `extension` example
* `@@||example.com^$extension` — userscripts won't work on all pages of the `example.com` website.
> **Compatibility with different versions of AdGuard.** Only AdGuard for Windows, Mac, Android are technically capable of using rules with `$extension` modifier.
<a id="stealth-modifier"></a>
##### **`stealth`**
@ -596,7 +600,7 @@ Disables the Stealth Mode module for all corresponding pages and requests.
* `@@||domain.com^$script,stealth,domain=example.com` — disables `Stealth Mode` only for script requests to `domain.com` (and its subdomains) on `example.com` and all its subdomains.
* Please note that blocking cookies and removing tracking parameters is achieved by using rules with `$cookie` and `$removeparam` modifiers. Exceptions with only `$stealth` modifier won't do those things. If you want to completely disable all Stealth Mode features for a given URL, you need to include all three modifiers: `@@||example.org^$stealth,removeparam,cookie`
> **Compatibility with different versions of AdGuard.** Stealth Mode is currently available in AdGuard for Windows, Mac, Android and AdGuard browser extensions for Chrome, Firefox, Edge. For now, the products that do not support Stealth Mode will ignore the rules with this modifier.
> **Compatibility with different versions of AdGuard.** Stealth Mode is available in AdGuard for Windows, Mac, Android, and AdGuard browser extensions for Chrome, Firefox, Edge. All other products will ignore the rules with `$stealth` modifier.
<a id="generic-rules"></a>
##### Generic rules
@ -638,13 +642,13 @@ Disables generic basic rules on pages that correspond to exception rule.
<a id="specifichide-modifier"></a>
##### **`specifichide`**
Has an opposite effect to [`generichide`](#generichide-modifier). Disables all specific element hiding and CSS rules, but not general ones.
Has an opposite effect to [`$generichide`](#generichide-modifier). Disables all specific element hiding and CSS rules, but not general ones.
* `@@||example.org^$specifichide` — will disable `example.org##.banner` but not `##.banner`.
> Please note that [`$elemhide` modifier](#elemhide-modifier) can disable all cosmetic rules at once.
> **Compatibility with different versions of AdGuard.** Rules with this modifier are supported by AdGuard for Windows, Mac, Android, and AdGuard browser extensions for Chrome, Firefox, Edge. **Developer builds only at this moment.**
> **Compatibility with different versions of AdGuard.** Rules with `$specifichide` modifier are supported by AdGuard for Windows, Mac, Android, and AdGuard browser extensions for Chrome, Firefox, Edge.
<a id="advanced-modifiers"></a>
### Advanced capabilities
@ -678,7 +682,7 @@ You can also use regular expressions to match query parameters and/or their valu
> **Escaping special characters**: don't forget to escape special characters like `,`, `/` and `$` in the regular expressions. Use `\` character for that purpose. For example, an escaped comma should look like this: `\,`.
> Important: note that regex-type rules target both parameter's name and value. In order to minimize the chance of mistakes, it is safer to start every regex with `/^` unless you specifically target parameter values.
> Please note that regex-type rules target both parameter's name and value. In order to minimize the chance of mistakes, it is safer to start every regex with `/^` unless you specifically target parameter values.
> We will try to detect and ignore unescaped `$` automatically using a simple rule of thumb:
> It is not an options delimiter if all three are true:
@ -752,44 +756,39 @@ With these rules, specified UTM parameters will be removed from any request save
> Please note that `$removeparam` rules can also be disabled by `$document` and `$urlblock` exception rules. But basic exception rules without modifiers don't do that. For example, `@@||example.com^` will not disable `$removeparam=p` for requests to **example.com**, but `@@||example.com^$urlblock` will.
> **Compatibility with different versions of AdGuard.** Rules with this modifier are supported by AdGuard for Windows, Mac, Android, and AdGuard browser extensions for Chrome, Firefox, Edge. **Developer builds only at this moment.**
> **Compatibility with different versions of AdGuard.** Rules with `$removeparam` modifier are supported by AdGuard for Windows, Mac, Android, and AdGuard browser extensions for Chrome, Firefox, Edge.
> **Restrictions.** Please note that this type of rules can be used **only in trusted filters**. This category includes your own **User filter** and all the filters created by AdGuard Team.
> **Restrictions.** Rules with `$removeparam` modifier can be used **only in trusted filters**. This category includes your own **User rules** and all the filters created by AdGuard Team.
<a id="important-modifier"></a>
#### **`important`**
The `$important` modifier applied to a rule increases its priority over any other rule without `$important` modifier. Even over basic exception rules.
##### Example 1:
##### Examples:
```
! blocking rule will block all requests despite of the exception rule
||example.org^$important
@@||example.org^
```
`||example.org^$important` will block all requests despite of the exception rule.
##### Example 2:
```
! if the exception rule also has `$important` modifier it will prevail, so no requests will not be blocked
||example.org^$important
@@||example.org^$important
```
Now the exception rule also has `$important` modifier so it will prevail.
##### Example 3:
The `$important` modifier will be ignored if a document-level exception rule is applied to the document.
```
! if a document-level exception rule is applied to the document, the `$important` modifier will be ignored;
! so if a request to `example.org` is sent from the `test.org` domain, the blocking rule will not be applied despite it has the `$important` modifier
||example.org^$important
@@||test.org^$document
```
If a request to `example.org` is sent from the `test.org` domain, the rule won't be applied despite it has the `$important` modifier.
<a id="badfilter-modifier"></a>
#### **`badfilter`**
@ -807,7 +806,7 @@ Rules with `$badfilter` modifier can disable other basic rules for specific doma
* The rule has a `$domain` modifier
* The rule does not have a negated domain `~` in `$domain` modifier's value.
In that case, the `$badfilter` rule will disable the corresponding rule for domains specified in both the `$badfilter` and basic rules. Please note, that [wildcard-TLD logic](https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#wildcard-for-tld) works here as well.
In that case, the `$badfilter` rule will disable the corresponding rule for domains specified in both the `$badfilter` and basic rules. Please note, that [wildcard-TLD logic](#wildcard-for-tld) works here as well.
**Examples:**
@ -821,28 +820,28 @@ In that case, the `$badfilter` rule will disable the corresponding rule for doma
<a id="empty-modifier"></a>
#### **`empty`**
> **Deprecation notice.** This modifier is deprecated in favor of the [`$redirect` modifier](#redirect-modifier). Rules with `$empty` are converting into `$redirect=nooptext` now.
Usually, blocked requests look like a server error to browser. If you use `empty` modifier, AdGuard will emulate a blank response from the server with` 200 OK` status.
##### `empty` example
* `||example.org^$empty` — returns an empty response to all requests to `example.org` and all subdomains.
> **Deprecation notice.** Rules with this modifier are deprecated in favor of the `$redirect` modifier. Please note that it will be removed in the future.
> **Compatibility with different versions of AdGuard.** Rules with this modifier are not supported by AdGuard for Safari and iOS.
> **Compatibility with different versions of AdGuard.** Rules with `empty` modifier are not supported by AdGuard Content Blocker, AdGuard for iOS and Safari.
<a id="mp4-modifier"></a>
#### **`mp4`**
> **Deprecation notice.** This modifier is deprecated in favor of the [`$redirect` modifier](#redirect-modifier). Rules with `$mp4` are converting into `$redirect=noopmp4-1s,media` now.
As a response to blocked request AdGuard returns a short video placeholder.
##### `mp4` example
* `||example.com/videos/$mp4` — block a video downloads from `||example.com/videos/*` and changes the response to a video placeholder.
> **Deprecation notice.** Rules with this modifier are deprecated in favor of the `$redirect` modifier. Please note that it will be removed in the future.
> **Compatibility with different versions of AdGuard.** Rules with this modifier are not supported by AdGuard for Safari and iOS.
> **Compatibility with different versions of AdGuard.** Rules with `mp4` modifier are not supported by AdGuard Content Blocker, AdGuard for iOS and Safari.
<a id="replace-modifier"></a>
#### **`replace`**
@ -907,9 +906,9 @@ http://regexr.com/3cesk
* `@@||example.org^$replace` will disable all `$replace` rules matching `||example.org^`.
* `@@||example.org^$document` or `@@||example.org^$content` will disable all `$replace` rules **originated from** pages of `example.org` **including the page itself**.
> **Compatibility with different versions of AdGuard.** These rules are supported by AdGuard for Windows, Mac, Android and by the AdGuard's Firefox add-on. This type of rules don't work in extensions for other browsers because they are unable to modify content on the network level.
> **Compatibility with different versions of AdGuard.** Rules with `$replace` modifier are supported by AdGuard for Windows, Mac, Android, and AdGuard browser extension for Firefox. Such rules do not work in extensions for other browsers because they are unable to modify content on the network level.
> **Restrictions.** Please note that this type of rules can be used **only in trusted filters**. This category includes your own **User filter** and all the filters created by AdGuard Team.
> **Restrictions.** Rules with `$replace` modifier can be used **only in trusted filters**. This category includes your own **User rules** and all the filters created by AdGuard Team.
<a id="csp-modifier"></a>
#### **`csp`**
@ -930,8 +929,8 @@ For the requests matching a `$csp` rule, we will strengthen response's security
>Limitations
>1. Please note that there're a few characters forbidden in the `$csp` value: (`,`), (`$`)
>2. `csp` rules support limited list of modifiers: `domain`, `important`, `subdocument`
>1. Please note that there're a few characters forbidden in the `$csp` value: `,`, `$`;
>2. `$csp` rules support limited list of modifiers: `$domain`, `$important`, `$subdocument`;
>3. Rules with `report-*` directives are considered invalid.
##### `csp` examples
@ -942,6 +941,8 @@ For the requests matching a `$csp` rule, we will strengthen response's security
* `||example.org^$csp=script-src 'self' 'unsafe-eval' http: https:` — disables inline scripts on all the pages matching the rule pattern.
* `@@||example.org^$document` or `@@||example.org^$urlblock` — disables all the `$csp` rules on all the pages matching the rule pattern.
> **Compatibility with different versions of AdGuard.** Rules with `$csp` modifier are not supported by AdGuard Content Blocker, AdGuard for iOS and Safari.
<a id="cookie-modifier"></a>
#### **`cookie`**
@ -960,7 +961,7 @@ The rule syntax depends on whether we are going to block all cookies or to remov
* `||example.org^$cookie=NAME` — blocks a single cookie named `NAME`
* `||example.org^$cookie=/regular_expression/` — blocks every cookie that matches a given regular expression
> **Important:** in the case of a regular expression matching, two characters must be escaped: comma (`,`) and (`$`). Use (`\`) for it. For example, escaped comma looks like this: `\,`.
> **Escaping special characters:** if regular expression is used for matching, two characters must be escaped: comma `,` and dollar sign `$`. Use backslash `\` escape each of them. For example, escaped comma looks like this: `\,`.
`$cookie` rules are not affected by regular exception rules (`@@`) unless it's a `$document` exception. In order to disable a `$cookie` rule, the exception rule should also have a `$cookie` modifier. Here's how it works:
@ -968,14 +969,14 @@ The rule syntax depends on whether we are going to block all cookies or to remov
* `@@||example.org^$cookie=NAME` — unblocks a single cookie named `NAME`
* `@@||example.org^$cookie=/regular_expression/` — unblocks every cookie matching a given regular expression
> **Limitations:** `$cookie` rules support a limited list of modifiers: `domain`, `~domain`, `important`, `third-party`, `~third-party`.
> **Limitations:** `$cookie` rules support a limited list of modifiers: `$domain`, `$~domain`, `$important`, `$third-party`, `~third-party`.
##### Real-life examples
* `$cookie=__cfduid` — blocks CloudFlare cookie everywhere
* `$cookie=/__utm[a-z]/` — blocks Google Analytics cookies everywhere
* `||facebook.com^$third-party,cookie=c_user` — prevents Facebook from tracking you even if you are logged in
> **Compatibility with different versions of AdGuard.** This type of rules is not supported by AdGuard for iOS and Safari.
> **Compatibility with different versions of AdGuard.** Rules with `$cookie` modifier are not supported by AdGuard Content Blocker, AdGuard for iOS and Safari.
<a id="network-modifier"></a>
#### **`network`**
@ -993,7 +994,7 @@ This is basically a Firewall-kind of rules allowing to fully block or unblock ac
* `174.129.166.49$network` — blocks access to `174.129.166.49:*`.
* `@@174.129.166.49$network` — makes AdGuard bypass data to the endpoint. No other rules will be applied.
> **Compatibility with different versions of AdGuard.** Only AdGuard for Windows, Mac, Android are technically capable of using this type of rules.
> **Compatibility with different versions of AdGuard.** Only AdGuard for Windows, Mac, Android are technically capable of using rules with `$network` modifier.
<a id="app-modifier"></a>
#### **`app`**
@ -1018,7 +1019,7 @@ If you want the rule not to be applied to certain apps, start the app name with
* `||baddomain.com^$app=~org.example.app` — a rule to block requests that match the specified mask, and are sent from any app save for the `org.example.app`.
* `||baddomain.com^$app=~org.example.app1|~org.example.app2` — same as above, but now two apps are excluded: `org.example.app1` and `org.example.app2`.
> **Compatibility with different versions of AdGuard.** Only AdGuard for Windows, Mac, Android are technically capable of using this type of rules.
> **Compatibility with different versions of AdGuard.** Only AdGuard for Windows, Mac, Android are technically capable of using rules with `$app` modifier.
<a id="redirect-modifier"></a>
@ -1030,7 +1031,7 @@ AdGuard is able to redirect web requests to a local "resource".
AdGuard uses the same filtering rules syntax as uBlock Origin. Also, it is compatible with ABP `$rewrite=abp-resource` modifier.
`$redirect` is a modifier for the [basic filtering rules](https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#basic-rules) so rules with this modifier support all other basic modifiers like `$domain`, `$third-party`, `$script`, etc.
`$redirect` is a modifier for the [basic filtering rules](#basic-rules) so rules with this modifier support all other basic modifiers like `$domain`, `$third-party`, `$script`, etc.
> The value of the `$redirect` modifier must be the name of the resource that will be used for redirection.
@ -1055,13 +1056,14 @@ This rule redirects all requests to `example.org/script.js` to the resource name
This rule redirects all requests to `example.org/test.mp4` to the resource named `noopmp4-1s`.
> More information on scriptlets, redirects, and their usage is available in [this GitHub section](https://github.com/AdguardTeam/Scriptlets#redirect-resources).
> More information on redirects and their usage is available [on GitHub](https://github.com/AdguardTeam/Scriptlets#redirect-resources).
> **Compatibility with different versions of AdGuard.** This type of rules is not supported by AdGuard for iOS and Safari.
> **Compatibility with different versions of AdGuard.** Rules with `$redirect` modifier are not supported by AdGuard Content Blocker, AdGuard for iOS and Safari.
<a id="redirect-rule-modifier"></a>
#### **`redirect-rule`**
This is basically an alias to `$redirect` since it has the same "redirection" values and the logic is almost similar. The difference is that `$redirect-rule` is applied only in the case when the target request is blocked by a different basic rule.
This is basically an alias to [`$redirect`](#redirect-modifier) since it has the same "redirection" values and the logic is almost similar. The difference is that `$redirect-rule` is applied only in the case when the target request is blocked by a different basic rule.
> Negating `$redirect-rule` works exactly the same way as for regular `$redirect` rules. Even more than that, `@@||example.org^$redirect` will negate both `$redirect` and `$redirect-rule` rules.
@ -1074,6 +1076,8 @@ Examples:
In this case, only requests to `example.org/script.js` will be "redirected". All other requests to `example.org` will be kept intact.
> **Compatibility with different versions of AdGuard.** Rules with `$redirect-rule` modifier are not supported by AdGuard Content Blocker, AdGuard for iOS and Safari.
<a id="denyallow-modifier"></a>
#### **`denyallow`**
@ -1111,6 +1115,8 @@ or to these three:
@@||y.com$script,domain=a.com|b.com
```
> **Compatibility with different versions of AdGuard.** Rules with `$denyallow` modifier are not supported by AdGuard Content Blocker.
<a id="noop-modifier"></a>
#### **`noop`**
@ -1123,7 +1129,7 @@ or to these three:
||example.com$replace=/bad/good/,___,~third-party
```
> **Compatibility with different versions of AdGuard.** Available in **Developer builds only at this moment.**
> **Compatibility with different versions of AdGuard.** Rules with `noop` modifier are not supported by AdGuard Content Blocker.
<a id="removeheader-modifier"></a>
#### **`$removeheader`**
@ -1222,7 +1228,7 @@ Use `@@` to negate `$removeheader`:
@@||example.org/path/$removeheader
```
> **Compatibility with different versions of AdGuard.** Available in **Developer builds only at this moment.**
> **Compatibility with different versions of AdGuard.** Rules with `$removeparam` modifier are supported by AdGuard for Windows, Mac, Android, and AdGuard browser extensions for Chrome, Firefox, Edge.
<a id="non-basic-rules"></a>
# Non-basic rules
@ -1239,7 +1245,7 @@ However, the capabilities of the basic rules may not be sufficient to block ads.
Element hiding rules are used to hide the elements of web pages. It is similar to applying `{ display: none; }` style to selected element.
> Note that element hiding rules may operate differently [depending on the platform](https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#cosmetic-rules-priority).
> Element hiding rules may operate differently [depending on the platform](#cosmetic-rules-priority).
<a id="elemhide-syntax"></a>
#### Syntax
@ -1254,14 +1260,14 @@ domains = [domain0, domain1[, ...[, domainN]]]
If you want to limit the rule application area to certain domains, just enter them separated with commas. For example: `example.org,example.com##selector`.
> Please note that this rule will be also applied to all subdomains of `example.org` and `example.com`.
> This rule will be also applied to all subdomains of `example.org` and `example.com`.
If you want the rule not to be applied to certain domains, start a domain name with `~` sign. For example:
`~example.org##selector`.
You can use both approaches in a single rule. For example, `example.org,~subdomain.example.org##domain` will work for `example.org` and all subdomains, **except `subdomain.example.org`**.
> **Please note,** element hiding rules are not dependent on each other. If there is a rule `example.org##selector` in the filter and you add `~example.org##selector` both rules will be applied independently.
> **Please note:** element hiding rules are not dependent on each other. If there is a rule `example.org##selector` in the filter and you add `~example.org##selector` both rules will be applied independently.
<a id="elemhide-examples"></a>
#### Examples
@ -1270,7 +1276,7 @@ You can use both approaches in a single rule. For example, `example.org,~subdoma
* `example.com,example.org###adblock` — hides an element with attribute `id` equals `adblock` at `example.com`, `example.org` and all subdomains.
* `~example.com##.textad` — hides an element with a class `textad` at all domains, except `example.com` and its subdomains.
> **Important!** Safari doesn't support both permitted and restricted domains. So the rules like `example.org,~foo.example.org##.textad` are invalid in AdGuard for Safari.
> **Limitations:** Safari does not support both permitted and restricted domains. So the rules like `example.org,~foo.example.org##.textad` are invalid in AdGuard for Safari.
<a id="elemhide-exceptions"></a>
#### Exceptions
@ -1308,7 +1314,7 @@ Sometimes, simple hiding of an element is not enough to deal with advertising. F
> **Compatibility with different versions of AdGuard.** CSS rules are not supported by AdGuard Content Blocker.
> Note that CSS rules may operate differently [depending on the platform](https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#cosmetic-rules-priority).
> CSS rules may operate differently [depending on the platform](#cosmetic-rules-priority).
<a id="cosmetic-css-rules-syntax"></a>
#### Syntax
@ -1356,15 +1362,15 @@ CSS 3.0 is not always enough to block ads. To solve this problem AdGuard extends
> **Application area.** Extended selectors can be used in any cosmetic rule, whether they are [element hiding rules](#cosmetic-elemhide-rules) or [CSS rules](#cosmetic-css-rules).
> **Compatibility with different versions of AdGuard.** Note that CSS rules are not supported by AdGuard Content Blocker.
> **Compatibility with different versions of AdGuard.** Rules with extended CSS selectors are not supported by AdGuard Content Blocker.
#### Syntax
Regardless of the CSS pseudo-classes you are using in the rule, you can use special markers to make these rules use the "Extended CSS" engine. It is recommended to use these markers for all "extended CSS" cosmetic rules so that it was easier to find them.
The syntax for extended CSS rules:
* `#?#` — for element hiding (`#@?#` — for exceptions )
* `#$?#` — for CSS injection (`#@$?#` — for exceptions )
* `#?#` — for element hiding, `#@?#` — for exceptions
* `#$?#` — for CSS rules, `#@$?#` — for exceptions
We **strongly recommend** using these markers any time when you use an extended CSS selector.
@ -1770,7 +1776,7 @@ div[class]:has(> a:not([id])) { remove: true; }
The way **element hiding** and **CSS rules** are applied is platform-specific.
**In AdGuard for Windows, Mac, and Android**, we use a stylesheet injected into the page. The priority of cosmetic rules is the same as any other websites' CSS stylesheet. But there is a limitation: [element hiding](https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#elemhide-rules) and [CSS](https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#cosmetic-css-rules) rules cannot override inline styles. In such cases, it's recommended to use extended selectors or HTML filtering.
**In AdGuard for Windows, Mac, and Android**, we use a stylesheet injected into the page. The priority of cosmetic rules is the same as any other websites' CSS stylesheet. But there is a limitation: [element hiding](#elemhide-syntax) and [CSS rules](#cosmetic-css-rules) cannot override inline styles. In such cases, it's recommended to use extended selectors or HTML filtering.
**In AdGuard browser extensions**, the so called "user stylesheets" are used. They have higher priority than even the inline styles.
@ -1781,7 +1787,7 @@ The way **element hiding** and **CSS rules** are applied is platform-specific.
In most cases, the basis and cosmetic rules are enough to filter ads. But sometimes it is necessary to change the HTML-code of the page itself before it is loaded. This is when you need filtering rules for HTML content. They allow to indicate the HTML elements to be cut out before the browser loads the page.
> **Compatibility with different versions of AdGuard.** Rules are supported by AdGuard for Windows, Mac, Android and by the AdGuard's Firefox add-on. This type of rules don't work in extensions for other browsers because they are unable to modify content on network level.
> **Compatibility with different versions of AdGuard.** HTML filtering rules are supported by AdGuard for Windows, Mac, Android, and AdGuard browser extension for Firefox. Such rules do not work in extensions for other browsers because they are unable to modify content on network level.
<a id="html-filtering-rules-syntax"></a>
### Syntax
@ -1904,7 +1910,7 @@ We recommend to use this kind of exceptions only if it is not possible to change
AdGuard supports a special type of rules that allows you to inject any javascript code to websites pages.
> **Restrictions.** Please note that this type of rules can be used **only in trusted filters**. This category includes your own **User filter** and all the filters created by AdGuard Team.
> **Restrictions.** Javascript rules can be used **only in trusted filters**. This category includes your own **User rules** and all the filters created by AdGuard Team.
> **Compatibility with different versions of AdGuard.** Javascript rules are not supported by AdGuard Content Blocker.
@ -1955,8 +1961,6 @@ Scriptlet is a JavaScript function that provides extended capabilities for conte
> AdGuard supports a lot of different scriptlets. Please note that in order to achieve cross-blocker compatibility, we also support syntax of uBO and ABP.
> **Compatibility with different versions of AdGuard.** Scriptlet rules are not supported by AdGuard Content Blocker.
<a id="scriptlets-syntax"></a>
### Syntax
```
@ -1974,13 +1978,16 @@ example.org#%#//scriptlet("abort-on-property-read", "alert")
```
This rule will be applied to example.org pages (and its subdomains) and will execute the "abort-on-property-read" scriptlet with the "alert" parameter.
Learn more [how to debug scriptlets](#debug-scriptlets).
More information about scriptlets can be found [on GitHub](https://github.com/AdguardTeam/Scriptlets#scriptlets).
> For more information on how to debug scriptlets, jump to [this section](#debug-scriptlets) of the article.
> **Compatibility with different versions of AdGuard.** Scriptlet rules are not supported by AdGuard Content Blocker.
<a id="non-basic-rules-modifiers"></a>
## Modifiers for non-basic type of rules
<a id="non-basic-rules-modifiers"></a>(#)
## Modifiers
Each rule can be modified using the modifiers described in the following paragraphs.
<a id="non-basic-rules-modifiers-syntax"></a>
@ -2001,29 +2008,30 @@ it's used for the escaping). Use `\` to escape them. For example, an escaped bra
this: `\]`.
<a id="non-basic-rules-modifiers-app"></a>
### app
`app` lets you narrow the rule coverage down to a specific application (or a list of applications).
### `app`
The modifier's behavior and syntax perfectly match the corresponding [$app modifier](https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#app) of basic rules.
`$app` modifier lets you narrow the rule coverage down to a specific application or a list of applications.
`app` examples:
The modifier's behavior and syntax perfectly match the corresponding [basic rules `$app` modifier](#app-modifier).
#### `app` examples:
* `[$app=org.example.app]example.com##.textad` — hides a `div` with a class `textad` at `example.com` and all subdomains in requests sent from the `org.example.app` Android app.
* `[$app=~org.example.app1|~org.example.app2]example.com##.textad` — hides a `div` with a class `textad` at `example.com` and all subdomains in requests sent from any app except `org.example.app1` and `org.example.app2`.
* `[$app=com.apple.Safari]example.org#%#//scriptlet('prevent-setInterval', 'check', '!300')`. This rule will apply the corresponding scriptlet only in Safari browser on Mac.
* `[$app=org.example.app]#@#.textad` — disables all `##.textad` rules for all domains while using `org.example.app`.
> **Compatibility with different versions of AdGuard.** This type of rules is supported by AdGuard for Windows, Mac and Android. **Developer builds only at this moment.**
> **Compatibility with different versions of AdGuard.** Such rules with `$app` modifier are supported by AdGuard for Windows, Mac and Android.
<a id="non-basic-rules-modifiers-domain"></a>
### domain
`domain` limits the rule application area to a list of domains (and their subdomains).
### `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
[$domain modifier](https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#domain) of
basic rules.
[basic rules `$domain` modifier](#domain-modifier).
`domain` examples:
#### `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.
@ -2035,12 +2043,13 @@ Please note that there are 2 ways to specify domain restrictions for non-basic r
But rules with mixed style domains restriction are considered invalid. So, for example, the rule
`[$domain=example.org]example.com##.textad` will be rejected.
> **Compatibility with different versions of AdGuard.** This type of rules is supported by AdGuard for Windows, Mac and Android. **Developer builds only at this moment.**
> **Compatibility with different versions of AdGuard.** Such rules with `$domain` modifier are supported by AdGuard for Windows, Mac, Android, and AdGuard browser extensions for Chrome, Firefox, Edge.
<a id="non-basic-rules-modifiers-path"></a>
### path
`path` limits the rule application area to specific locations or pages on websites.
### `path`
`$path` modifier limits the rule application area to specific locations or pages on websites.
#### Syntax
```
@ -2052,9 +2061,9 @@ path=pattern
> Please note that `path` modifier matches the query string as well.
> `path` modifier supports regular expressions in [the same way](#regexp-support) basic rules do.
> `$path` modifier supports regular expressions in [the same way](#regexp-support) basic rules do.
`path` examples:
#### `path` examples:
* `[$path=page.html]##.textad` — hides a `div` with a class `textad` at `/page.html` or `/page.html?<query>` or `/sub/page.html` or `/another_page.html`
* `[$path=/page.html]##.textad` — hides a `div` with a class `textad` at `/page.html` or `/page.html?<query>` or `/sub/page.html` of any domain but not at `/another_page.html`
* `[$path=|/page.html]##.textad` — hides a `div` with a class `textad` at `/page.html` or `/page.html?<query>` of any domain but not at `/sub/page.html`
@ -2063,7 +2072,7 @@ path=pattern
* `[$domain=example.com,path=/page.html]##.textad` — hides a `div` with a class `textad` at `page.html` of `example.com` and all subdomains but not at `another_page.html`
* `[$path=/\\/(sub1|sub2)\\/page\\.html/]##.textad` — hides a `div` with a class `textad` at both `/sub1/page.html` and `/sub2/page.html` of any domain (please, note the [escaped special characters](#non-basic-rules-modifiers-syntax))
> **Compatibility with different versions of AdGuard.** Rules with `path` modifier are supported by AdGuard for Windows, Mac, Android, and AdGuard browser extensions for Chrome, Firefox, Edge.
> **Compatibility with different versions of AdGuard.** Rules with `$path` modifier are supported by AdGuard for Windows, Mac, Android, and AdGuard browser extensions for Chrome, Firefox, Edge.
<a id="for_maintainers"></a>
## Information for filters maintainers
@ -2249,8 +2258,7 @@ Eventually, here are the two versions of the Base filter for AdGuard browser ext
- full: https://filters.adtidy.org/extension/chromium/filters/2.txt
- optimized: https://filters.adtidy.org/extension/chromium/filters/2_optimized.txt
**Important: If you want to add a rule which shouldn't be removed at optimization use the NOT_OPTIMIZED hint:**
**If you want to add a rule which shouldn't be removed at optimization use the `NOT_OPTIMIZED` hint:**
```
!+ NOT_OPTIMIZED
@ -2294,14 +2302,14 @@ Specify which platforms can apply this rule. List of existing platforms:
Examples:
This rule will be available for Windows, Mac, and Android only:
This rule will be available only in AdGuard for Windows, Mac, Android:
```
!+ PLATFORM(windows,mac,android)
||example.org^
```
This rule will be available for every platform except Safari extension, iOS, and Android content blocker:
This rule will be available for every platform except AdGuard for Safari, Android Content Blocker, and AdGuard for iOS:
```
!+ NOT_PLATFORM(ext_safari, ext_android_cb, ios)
@ -2382,7 +2390,7 @@ ExtendedCss.query(selectorText) // returns an array of Elements matching selecto
<a id="debug-scriptlets"></a>
### Debugging scriptlets
If you're using AdGuard browser extension and want to debug a [scriptlet rule](https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#scriptlets), you can get additional information by simply having the Filtering log opened. In that case, scriptlets will switch to debug mode and will write more information to the browser's console.
If you're using AdGuard browser extension and want to debug a [scriptlet rule](#scriptlets), you can get additional information by simply having the Filtering log opened. In that case, scriptlets will switch to debug mode and will write more information to the browser's console.
The following scriptlets are especially developed for debug purposes:

View File

@ -287,7 +287,7 @@ pattern = "/" regexp "/"
Например, правило `/banner\d+/$third-party` применит регулярное выражение `banner\d+` ко всем сторонним запросам. Правила-исключения с использованием регулярных выражений выглядят вот так: `@@/banner\d+/`.
> **Совместимость с различными версиями AdGuard.** Браузерные расширения AdGuard для Safari и AdGuard для iOS не полностью поддерживают регулярные выражения в силу [ограничений Content Blocking API](https://webkit.org/blog/3476/content-blockers-first-look/) (в статье по ссылке найдите раздел "The Regular expression format").
> **Совместимость с разными версиями 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)
@ -295,7 +295,7 @@ pattern = "/" regexp "/"
Вы можете использовать wildcard-символ для доменов верхнего уровня в паттернах косметических, html и js правил. Например, правило `example.*##.banner` будет соответствовать всем `example.TLD` доменам: `example.ru`, `example.com`, `example.net`, `example.org` и т.д.
При составлении базовых правил вы можете использовать *wildcard-символ для TLD* только вместе с модификатором `$domain`. Например, `||*/banners/*$image,domain=example.*`
> **Совместимость с различными версиями AdGuard.** Поддерживается: AdGuard для Windows/macOS/Android/Safari/iOS и браузерными расширениями для Chrome/Firefox/Edge.
> **Совместимость с разными версиями AdGuard.** Правила с wildcard для TLD поддерживается в AdGuard для Windows, Mac, Android, Safari, iOS и в браузерном расширении AdGuard для Chrome, Firefox, Edge.
<a id="basic-rules-examples"></a>
### Примеры базовых правил
@ -353,9 +353,9 @@ pattern = "/" regexp "/"
Если будет выполняться условие `1 и ((2 и 3) или 4)`, то модификатор `$domain` будет соответствовать как домену-рефереру, так и целевому домену. То есть, если модификатор `$domain` содержит только исключённые домены, то правилу не нужно выполнять второе и третье условия, чтобы соответствовать целевому домену `$domain`.
Если какие-либо из условий выше не выполнены, но правило содержит модификатор `cookie` или `csp`, модификатор `domain` всё равно будет соответствовать целевому домену.
Если какие-либо из условий выше не выполнены, но правило содержит модификатор [`$cookie`](#cookie-modifier) или [`$csp`](#csp-modifier), модификатор `$domain` всё равно будет соответствовать целевому домену.
Если реферер соответствует правилу с `domain`, которое явно исключает домен реферера, то правило не сработает, даже если целевой домен тоже ему соответствует. Это также касается правил с модификаторами `cookie` и `csp`.
Если реферер соответствует правилу с `$domain`, которое явно исключает домен реферера, то правило не сработает, даже если целевой домен тоже ему соответствует. Это также касается правил с модификаторами [`$cookie`](#cookie-modifier) и [`$csp`](#csp-modifier).
**Примеры:**
@ -371,7 +371,7 @@ pattern = "/" regexp "/"
* `/banner\d+/$domain=targetdomain.com` не сработает, поскольку правило содержит регулярное выражение.
* `page$domain=targetdomain.com|~example.org` не сработает, так как домен реферера явно исключён.
> **Важно!** Safari не поддерживает одновременно разрешенные и запрещенные домены, поэтому правила вида `||baddomain.com^$domain=example.org|~foo.example.org` не действуют в AdGuard для Safari.
> **Ограничения:** Safari не поддерживает одновременно разрешенные и запрещенные домены, поэтому правила вида `||baddomain.com^$domain=example.org|~foo.example.org` не работают в AdGuard для Safari.
<a id="third-party-modifier"></a>
##### **`third-party`**
@ -382,13 +382,13 @@ pattern = "/" regexp "/"
> 1) Он не должен быть отправлен с поддомена того же домена или наоборот. Например, запрос к `subdomain.example.org`, отправленный с домена `example.org`, не является сторонним.
> 2) Его заголовок `Sec-Fetch-Site` имеет значение `cross-site`.
Если указан модификатор `third-party`, то правило применяется только к сторонним запросам.
Если указан модификатор `$third-party`, то правило применяется только к сторонним запросам.
###### Примеры `third-party`
* `||domain.com^$third-party` — правило применяется на всех сайтах, кроме `domain.com` и его поддоменов. Пример стороннего запроса: `http://example.org/banner.jpg`.
Если указан модификатор `~third-party`, то правило применяется только к запросам, которые не являются сторонними. То есть, эти запросы отправлены с того же домена.
Если указан модификатор `$~third-party`, то правило применяется только к запросам, которые не являются сторонними. То есть, эти запросы отправлены с того же домена.
###### Примеры `~third-party`
@ -405,7 +405,7 @@ AdGuard будет пытаться закрыть браузерную вкла
>Модификатор может не работать, если всплывающая страница закеширована браузером. Также модификатор может не сработать, если для показа попапа используются нестандартные методы. В такие случаях лучше использовать расширение [AdGuard Popup Blocker](https://github.com/AdguardTeam/PopupBlocker).
>**Важно!** В отличие от браузерных расширений, модификатор `$popup` крайне нестабильно работает с приложениями AdGuard для Windows, Mac и Android. В AdGuard для Safari и iOS `$popup`-правила просто заблокируют страницу.
>**Обратите внимание:** В отличие от браузерных расширений, модификатор `$popup` крайне нестабильно работает с приложениями AdGuard для Windows, Mac и Android. В AdGuard для Safari и iOS `$popup`-правила просто заблокируют страницу.
<a id="match-case-modifier"></a>
@ -422,7 +422,7 @@ AdGuard будет пытаться закрыть браузерную вкла
Существует целый набор модификаторов, которые ограничивают действие правила только запросами к ресурсам определенного типа. Эти модификаторы можно комбинировать, например распространить правило одновременно на картинки и скрипты.
> **Совместимость с разными версиями AdGuard.** Существует большая разница в том, как разные версии AdGuard определяют тип контента. В случае браузерных расширений тип контента для каждого запроса предоставляется самим браузером. В случае AdGuard для Windows, macOS и Android для определения используется следующая методика: вначале мы пытаемся определить тип запроса по расширению загружаемого файла. Если запрос не заблокирован на этом этапе, то тип запроса уточняется с использованием заголовка `Content-Type` в начале ответа, полученного от сервера.
> **Совместимость с разными версиями AdGuard.** Существует большая разница в том, как разные версии AdGuard определяют тип контента. В случае браузерных расширений тип контента для каждого запроса предоставляется самим браузером. В случае AdGuard для Windows, Mac, Android для определения используется следующая методика: вначале мы пытаемся определить тип запроса по расширению загружаемого файла. Если запрос не заблокирован на этом этапе, то тип запроса уточняется с использованием заголовка `Content-Type` в начале ответа, полученного от сервера.
<a id="content-type-modifiers-examples"></a>
##### Примеры ограничений
@ -440,8 +440,6 @@ AdGuard будет пытаться закрыть браузерную вкла
Если этот модификатор используется в правиле-исключении (`@@`), то оно полностью отключает блокировку на соответствующих страницах. Это равносильно одновременному использованию модификаторов `$elemhide`, `$content`, `$urlblock`, `$jsinject` и `$extension`.
> **Совместимость с различными версиями AdGuard.** Логика блокировки типов запросов теперь поддерживается только dev-сборкой AdGuard.
###### Примеры `document`
* `@@||example.com^$document` — полностью отключает фильтрацию на всех страницах сайта `example.com` и всех его поддоменах.
@ -452,8 +450,9 @@ AdGuard будет пытаться закрыть браузерную вкла
* `||example.com^$document,removeparam=test` — удаляет параметр `test` из запроса HTML-документа к `example.com`.
* `||example.com^$document,replace=/test1/test2/` — заменяет `test1` на `test2` в запросе HTML-документа к `example.com`.
<a id="image-modifier"></a>
> **Совместимость с разными версиями AdGuard.** Правила блокировки с модификатором `$document` не поддерживаются в AdGuard Content Blocker.
<a id="image-modifier"></a>
##### **`image`**
Правило будет соответствовать запросам к изображениям.
@ -461,25 +460,24 @@ AdGuard будет пытаться закрыть браузерную вкла
<a id="stylesheet-modifier"></a>
##### **`stylesheet`**
Правило будет соответствовать запросам к файлам CSS стилей.
Правило будет соответствовать запросам к файлам CSS-стилей.
<a id="script-modifier"></a>
##### **`script`**
Правило будет соответствовать запросам к файлам скриптов (например javascript, vbscript).
Правило будет соответствовать запросам к файлам скриптов, например, javascript или vbscript.
<a id="object-modifier"></a>
##### **`object`**
Правило применяется к ресурсам, управляемым браузерными плагинами (например, Java или Flash).
Правило применяется к ресурсам, управляемым браузерными плагинами, например, Java или Flash.
<a id="object-subrequest-modifier"></a>
##### **`object-subrequest`**
Запросы, инициированные плагинами (чаще всего это Flash).
> **Предупреждение об устаревании.** Модификатор `$object-subrequest` устарел и больше не поддерживается. Правила с его использованием не работают.
> #### Совместимость с разными версиями AdGuard
> AdGuard для Windows, macOS и Android часто не могут корректно определить этот тип, и определяют его как `other`.
Запросы, инициированные плагинами (чаще всего это Flash).
<a id="font-modifier"></a>
##### **`font`**
@ -489,37 +487,39 @@ AdGuard будет пытаться закрыть браузерную вкла
<a id="media-modifier"></a>
##### **`media`**
Правило будет соответствовать запросам к медиа-файлам (музыка и видео, например, файлы с расширением .mp4).
Правило будет соответствовать запросам к медиа-файлам музыка и видео, например, файлы с расширением .mp4.
<a id="subdocument-modifier"></a>
##### **`subdocument`**
Правило будет соответствовать запросам к встроенным страницам (HTML-теги `frame` и `iframe`).
Правило будет соответствовать запросам к встроенным страницам — HTML-теги `frame` и `iframe`.
<a id="ping-modifier"></a>
##### **`ping`**
Правило будет соответствовать запросам, сделанным либо `navigator.sendBeacon()`, либо атрибутом ссылки `ping`.
> **Совместимость с разными версиями AdGuard.** AdGuard для Windows, macOS и Android не всегда могут корректно определить `navigator.sendBeacon()`. Для надёжного определения используйте браузерные расширения AdGuard.
> **Совместимость с разными версиями AdGuard.** AdGuard для Windows, Mac, Android не всегда могут корректно определить `navigator.sendBeacon()`. Для надёжного определения используйте браузерные расширения AdGuard.
<a id="xmlhttprequest-modifier"></a>
##### **`xmlhttprequest`**
Правило применяется только к ajax-запросам. То есть к запросам, отправленным с помощью javascript-объекта `XMLHttpRequest`.
> **Совместимость с разными версиями AdGuard.** AdGuard для Windows, macOS и Android не всегда могут корректно определить этот тип контента, и определяют его как `other` или `script`.
> **Совместимость с разными версиями AdGuard.** AdGuard для Windows, Mac и Android не всегда могут корректно определить этот тип контента, и определяют его как [`$other`](#other-modifier) или [`$script`](#script-modifier).
<a id="websocket-modifier"></a>
##### **`websocket`**
Правило применяется только к WebSocket-соединениям.
> **Совместимость с разными версиями AdGuard.** AdGuard для Safari и iOS не могут правильно применять этот модификатор из-за ограничений Safari.
> **Совместимость с разными версиями AdGuard.** AdGuard для Safari и iOS не могут правильно применять правила с модификатором `$websocket` из-за ограничений Safari.
<a id="webrtc-modifier"></a>
##### **`webrtc`**
> **Предупреждение об устаревании.** Модификатор `$webrtc` устарел и в будущем его поддержка прекратиться. Если вы хотите блокировать WebRTC, рассмотрите возможность использования [скриптлета](#scriptlets) `nowebrtc`.
Правило применяется только к WebRTC-соединениям.
> Обратите внимание, что блокировка WebRTC может мешать работе некоторых браузерных приложений, таких как мессенджеры, чаты, кинотеатры, игры и др.
@ -529,7 +529,7 @@ AdGuard будет пытаться закрыть браузерную вкла
* `||example.com^$webrtc,domain=example.org` — это правило блокирует WebRTC-соединения c `example.com` для `example.org`.
* `@@*$webrtc,domain=example.org` — это правило отменяет блокировку всех WebRTC-соединений для `example.org`.
> **Предупреждение об устаревании.** Этот модификатор устарел и в будущем его поддержка будет убрана. Если вы хотите блокировать WebRTC, рассмотрите возможность использования скриптлета `$nowebrtc`.
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$webrtc` всё ещё поддерживаются браузерным расширением AdGuard.
<a id="other-modifier"></a>
##### **`other`**
@ -582,12 +582,14 @@ AdGuard будет пытаться закрыть браузерную вкла
<a id="extension-modifier"></a>
##### **`extension`**
Отключает все пользовательские скрипты на страницах, подходящих под это правило. Этот модификатор имеет смысл только в продуктах AdGuard, которые могут работать как userscript hosts (AdGuard для Windows/macOS/Android).
Отключает все пользовательские скрипты на страницах, подходящих под это правило.
###### `extension` example
* `@@||example.com^$extension` — пользовательские скрипты не будут работать на всех страницах сайта `example.com`.
> **Совместимость с разными версиями AdGuard.** Только AdGuard для Windows, Mac, Android имеют технические возможности для поддержки правил с модификатором `$extension`.
<a id="stealth-modifier"></a>
##### **`stealth`**
@ -599,7 +601,7 @@ AdGuard будет пытаться закрыть браузерную вкла
* `@@||domain.com^$script,stealth,domain=example.com` — отключает модуль `Антитрекинг` только для script-запросов к `domain.com` (и поддоменам) на `example.com` и всех его поддоменах.
* Блокировка cookies и скрытие параметров отслеживания достигается использованием правил с модификаторами `$cookie` и `$removeparam`. Правила-исключения только с модификатором `$stealth` не дадут желаемого результата. Если вы хотите полностью отключить все функции Антитрекинга для определённого домена, вам надо включить в правило все три модификатора: `@@||example.org^$stealth,removeparam,cookie`
> **Совместимость с разными версиями AdGuard.** Антитрекинг на данный момент доступен в AdGuard для Windows, Mac, Android и в браузерных расширениях AdGuard для Chrome, Firefox, Edge. Пока что продукты, не поддерживающие Антитрекинг, будут игнорировать этот модификатор.
> **Совместимость с разными версиями AdGuard.** Антитрекинг доступен в AdGuard для Windows, Mac, Android и в браузерных расширениях AdGuard для Chrome, Firefox, Edge. Все остальные продукты будут игнорировать правила с модификатором `$stealth`.
<a id="generic-rules"></a>
##### Generic правила
@ -641,13 +643,13 @@ domain.com###banner
<a id="specifichide-modifier"></a>
##### **`specifichide`**
Имеет эффект, противоположный [`generichide`](#generichide-modifier). Отключает все "specific" правила сокрытия элементов и CSS-правила, но не отключает "general"-правила.
Имеет эффект, противоположный [`$generichide`](#generichide-modifier). Отключает все "specific" правила сокрытия элементов и CSS-правила, но не отключает "general"-правила.
* `@@||example.org^$specifichide` — отключит `example.org##.banner`, но не `##.banner`.
> Обратите внимание, что [модификатор `$elemhide`](#elemhide-modifier) может отключить все косметические правила разом.
> **Совместимость с разными версиями AdGuard.** Правила с этим модификатором поддерживаются AdGuard для Windows, Mac, Android,а также браузерными расширениями AdGuard для Chrome, Firefox, Edge. **На данный момент только в девелопер-сборках.**
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$specifichide` поддерживаются в AdGuard для Windows, Mac, Android, а также браузерными расширениями AdGuard для Chrome, Firefox, Edge.
<a id="advanced-modifiers"></a>
### Расширенные возможности
@ -681,7 +683,7 @@ domain.com###banner
> **Экранирование специальных символов**: не забудьте экранировать специальные символы в регулярных выражениях, такие как `,`, `/` и `$`. Для этой цели используйте символ `\`. Например, экранированная запятая должна выглядеть так: `\,`.
> Важно: заметьте, что правила с регулярными выражениями смотрят как на имя, так и на значение параметра. Чтобы минимизировать риск ошибки, рекомендуем начинать регулярное выражение с `/^`, если только вы не хотите специально работать с значениями параметров.
> Обратите внимание, что правила с регулярными выражениями смотрят как на имя, так и на значение параметра. Чтобы минимизировать риск ошибки, рекомендуем начинать регулярное выражение с `/^`, если только вы не хотите специально работать с значениями параметров.
> Мы будем стараться обнаруживать и игнорировать неэкранированные символы `$` автоматически, используя следующее правило большого пальца:
> Это не является разделителем опций, если:
@ -748,48 +750,43 @@ $removeparam=/^(utm_content|utm_campaign|utm_referrer)=/
> **Обратите внимание**, что блокировку правил `$removeparam` также можно отключить с помощью правил исключений `$document` и `$urlblock`. Но базовые правила исключений без модификаторов не могут этого сделать. Например, `@@||example.com^` не отключит `$removeparam=p` для запросов к example.com, а вот `@@||example.com^$urlblock` — отключит.
> **Совместимость с различными версиями AdGuard.** Правила с этим модификатором поддерживаются AdGuard для Windows, Mac, Android, а также браузерными расширениями AdGuard для Chrome, Firefox, Edge. **На данный момент только девелопер-сборки.**
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$removeparam` поддерживаются в AdGuard для Windows, Mac, Android, а также браузерными расширениями AdGuard для Chrome, Firefox, Edge.
> **Ограничения.** Этот тип правил может быть использован **только в доверенных фильтрах** — то есть в **Пользовательских правилах** и всех фильтрах, разработанных командой AdGuard.
> **Ограничения.** Правила с модификатором `$removeparam` могут быть использованы **только в доверенных фильтрах** — то есть в **Пользовательских правилах** и всех фильтрах, разработанных командой AdGuard.
<a id="important-modifier"></a>
##### **`important`**
Модификатор `$important`, применённый к правилу, повышает его приоритет относительно любого другого правила без модификатора `$important`, даже относительно базовых правил-исключений.
###### Пример 1:
###### Примеры:
```
! блокирующее правило заблокирует все запросы, несмотря на правило-исключение.
||example.org^$important
@@||example.org^
```
`||example.org^$important` заблокирует все запросы, несмотря на правило-исключение.
###### Пример 2:
```
! если правило-исключение тоже имеет модификатор `$important`, оно будет иметь более высокий приоритет, и запросы не будут заблокированы
||example.org^$important
@@||example.org^$important
```
Теперь правило-исключение также имеет модификатор `$important`, так что оно будет иметь более высокий приоритет.
###### Пример 3:
Модификатор `$important` будет проигнорирован, если применяется правило-исключение на уровне документа.
```
! если применяется правило-исключение на уровне документа, модификатор `$important` будет проигнорирован;
! если запрос к `example.org` отправлен с домена `test.org`, блокирующее правило не будет применено, несмотря на наличие модификатора `$important`
||example.org^$important
@@||test.org^$document
```
Если запрос к `example.org` отправлен с домена `test.org`, правило не будет применено несмотря на наличие модификатора `$important`.
<a id="badfilter-modifier"></a>
##### **`badfilter`**
Правила, содержащие модификатор `badfilter`, отключают базовые правила, на которые они ссылаются. Это означает, что текст отключенного правила должен соответствовать тексту `badfilter`-правила (за исключением самого модификатора `badfilter`).
Правила, содержащие модификатор `$badfilter`, отключают базовые правила, на которые они ссылаются. Это означает, что текст отключенного правила должен соответствовать тексту `$badfilter`-правила (за исключением самого модификатора `$badfilter`).
**Примеры:**
@ -803,7 +800,7 @@ $removeparam=/^(utm_content|utm_campaign|utm_referrer)=/
* Правило имеет модификатор `$domain`
* Правило не имеет отрицания домена `~` в значении модификатора `$domain`.
В этом случае, правило с `$badfilter` отключит соответствующее базовое правило для доменов, указанных как в правиле с `$badfilter`, так и в базовом правиле. Обратите внимание, что [логика wildcard для доменов верхнего уровня (TLD)](https://kb.adguard.com/ru/general/how-to-create-your-own-ad-filters#wildcard-for-tld) здесь также применима.
В этом случае, правило с `$badfilter` отключит соответствующее базовое правило для доменов, указанных как в правиле с `$badfilter`, так и в базовом правиле. Обратите внимание, что [логика wildcard для доменов верхнего уровня (TLD)](#wildcard-for-tld) здесь также применима.
**Примеры:**
@ -817,28 +814,28 @@ $removeparam=/^(utm_content|utm_campaign|utm_referrer)=/
<a id="empty-modifier"></a>
##### **`empty`**
Обычно заблокированный запрос выглядит для браузера как ошибка сервера. В случае применения модификатора `empty`, AdGuard эмулирует пустой ответ сервера со статусом `200 OK`.
> **Предупреждение об устаревании.** Этот модификатор считаются устаревшими. Вместо него теперь используется [модификатор `$redirect`](#redirect-modifier). Правила с `$empty` конвертируются в `$redirect=nooptext`.
Обычно заблокированный запрос выглядит для браузера как ошибка сервера. В случае применения модификатора `$empty`, AdGuard эмулирует пустой ответ сервера со статусом `200 OK`.
###### Примеры `empty`
* `||example.org^$empty` — возвращает пустой ответ для всех запросов к домену `example.org` и всех его поддоменов.
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$empty` не поддерживаются в AdGuard Content Blocker, AdGuard для Safari и для iOS.
<a id="mp4-modifier"></a>
##### **`mp4`**
В качестве ответа на заблокированный запрос AdGuard возвращает короткое видео-заглушку.
> **Предупреждение об устаревании.** Этот модификатор считаются устаревшими. Вместо него теперь используется [модификатор `$redirect`](#redirect-modifier). Правила с `$mp4` конвертируются в `$redirect=noopmp4-1s,media`.
> **Предупреждение об устаревании.** Правила с этим модификатором считаются устаревшими. Вместо них теперь используется модификатор `$redirect`. Учтите, что скоро поддержка модификатора mp4 прекратится.
> **Совместимость с различными версиями AdGuard.** Правила с этим модификатором не поддерживаются в AdGuard для Safari и для iOS.
В качестве ответа на заблокированный запрос AdGuard возвращает короткую видео-заглушку.
###### Примеры `mp4`
* `||example.com/videos/$mp4` — блокирует загрузку видео с адресов `||example.com/videos/*` и заменяет ответ на видео-заглушку.
> **Предупреждение об устаревании.** Правила с этим модификатором считаются устаревшими. Вместо них теперь используется модификатор `$redirect`. Учтите, что скоро поддержка модификатора mp4 прекратится.
> **Совместимость с различными версиями AdGuard.** Правила с этим модификатором не поддерживаются в AdGuard для Safari и для iOS.
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$mp4` не поддерживаются в AdGuard Content Blocker, AdGuard для Safari и для iOS.
<a id="replace-modifier"></a>
##### **`replace`**
@ -902,9 +899,9 @@ http://regexr.com/3cesk
* `@@||example.org^$replace` отключит все правила `$replace`, соответствующие `||example.org^`.
* `@@||example.org^$document` или `@@||example.org^$content` отключит все правила `$replace`, **исходящие** со страниц домена `example.org`, **включая саму эту страницу**.
> **Совместимость с различными версиями AdGuard.** Эти правила поддерживаются AdGuard для Windows, Mac, Android и браузерным расширением AdGuard для Firefox. Этот тип правил не работает в расширениях для других браузеров, потому что они не могут модифицировать содержимое страниц на сетевом уровне.
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$replace` поддерживаются в AdGuard для Windows, Mac, Android и браузерным расширением AdGuard для Firefox. Такие правила не работают в расширениях для других браузеров, потому что они не могут модифицировать содержимое страниц на сетевом уровне.
> **Ограничения.** Пожалуйста, заметьте, что этот тип правил может быть использован **только в доверенных фильтрах**. Эта категория включает в себя **Пользовательские правила**, а также все фильтры, разработанные командой AdGuard.
> **Ограничения.** Правила с модификатором `$replace` могут быть использованы **только в доверенных фильтрах**. Эта категория включает в себя **Пользовательские правила**, а также все фильтры, разработанные командой AdGuard.
<a id="csp-modifier"></a>
##### **`csp`**
@ -925,8 +922,8 @@ http://regexr.com/3cesk
>Ограничения
>1. Некоторые символы запрещены в значении `$csp`: (`,`), (`$`)
>2. `$csp`-правила поддерживают ограниченный список модификаторов: `domain`, `important`, `subdocument`
>1. Некоторые символы запрещены в значении `$csp`: `,`, `$`
>2. `$csp`-правила поддерживают ограниченный список модификаторов: `$domain`, `$important`, `$subdocument`;
>3. Правила с директивами `report-*` считаются некорректными.
###### Примеры `$csp`
@ -937,6 +934,8 @@ http://regexr.com/3cesk
* `||example.org^$csp=script-src 'self' 'unsafe-eval' http: https:` — отключает инлайн-скрипты на всех страницах, подходящих под паттерн правила.
* `@@||example.org^$document` или `@@||example.org^$urlblock` — отключает все `$csp`-правила на всех страницах, подходящих под паттерн правила.
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$csp` не поддерживается в AdGuard Content Blocker, AdGuard для iOS и для Safari.
<a id="cookie-modifier"></a>
##### **`cookie`**
@ -955,7 +954,7 @@ http://regexr.com/3cesk
* `||example.org^$cookie=NAME` — Блокирует единственную cookie с именем `NAME`.
* `||example.org^$cookie=/regular_expression/` — Блокирует все cookie, которые совпадают с регулярным выражением.
> **Важно:** В случае использования регулярных выражений необходимо экранировать следующие символы: запятая (`,`) и (`$`). Используйте (`\`) для этого. Например, экранированная запятая выглядит так: `\,`.
> **Экранирование специальных символов:** в случае использования регулярных выражений необходимо экранировать запятую `,` и знак доллара `$`. Используйте для этого бекслеш `\`. Например, экранированная запятая выглядит так: `\,`.
Правила исключения (`@@`) не влияют на правила `$cookie`, только если это не правило исключение `$document`. Чтобы отключить правило `$cookie`, правило исключение также должно иметь модификатор `$cookie`. Вот как это работает:
@ -963,15 +962,14 @@ http://regexr.com/3cesk
* `@@||example.org^$cookie=NAME` — разблокирует одну cookie с именем `NAME`
* `@@||example.org^$cookie=/regular_expression/` — разблокирует все cookie, соответствующие заданному регулярному выражению
> **Ограничения**
> `$cookie` правила поддерживают ограниченный список модификаторов: `domain`, `~domain`, `important`, `third-party`, `~third-party`.
> **Ограничения:** `$cookie` правила поддерживают ограниченный список модификаторов: `$domain`, `$~domain`, `$important`, `$third-party`, `$~third-party`.
### Примеры с `$cookie`
* `$cookie=__cfduid` — блокирует CloudFlare cookie везде
* `$cookie=/__utm[a-z]/` — блокирует Google Analytics cookie везде
* `||facebook.com^$third-party,cookie=c_user` — не позволяет Facebook'у отслеживать вас, даже если вы вошли в систему
> **Совместимость с различными версиями AdGuard.** Этот тип правил не поддерживается AdGuard для iOS и для Safari.
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$cookie` не поддерживается в AdGuard Content Blocker, AdGuard для iOS и для Safari.
<a id="network-modifier"></a>
##### **`network`**
@ -989,7 +987,7 @@ http://regexr.com/3cesk
* `174.129.166.49$network` — блокирует доступ к `174.129.166.49:*`.
* `@@174.129.166.49$network` — заставляет AdGuard направлять трафик в конечную точку. Никакие другие правила не будут применены.
> **Совместимость с различными версиями AdGuard.** Только AdGuard для Windows, Mac, Android имеют технические возможности для поддержки этого типа правил.
> **Совместимость с разными версиями AdGuard.** Только AdGuard для Windows, Mac, Android имеют технические возможности для поддержки правила с модификатором `$network`.
<a id="app-modifier"></a>
##### **`app`**
@ -1002,19 +1000,19 @@ http://regexr.com/3cesk
>На Mac вы можете найти bundle ID или имя процесса интересующего вас приложения в деталях соответствующих запросов в Журнале фильтрации.
###### Примеры использования `app`
###### Примеры `app`
* `||baddomain.com^$app=org.example.app` — правило для блокирования запросов, подходящих под заданную маску и посылаемых Android-приложением `org.example.app`.
* `||baddomain.com^$app=org.example.app1|org.example.app2` — аналогичное правило, но оно работает как для приложения `org.example.app1`, так и для `org.example.app2`.
Если вы хотите, чтобы правило не применялось к заданному приложению, предваряйте имя приложения символом `~`.
###### Примеры использования `app` и `~`
###### Примеры `app` и `~`
* `||baddomain.com^$app=~org.example.app` — правило, блокирующее запросы, подходящие под заданную маску и посылаемые любым приложением кроме `org.example.app`.
* `||baddomain.com^$domain=~org.example.app1|~org.example.app2` — аналогично, но в исключениях два приложения: `org.example.app1` и `org.example.app2`.
* `||baddomain.com^$app=~org.example.app1|~org.example.app2` — аналогично, но в исключениях два приложения: `org.example.app1` и `org.example.app2`.
> **Совместимость с различными версиями AdGuard.** Только AdGuard для Windows, Mac, Android имеют технические возможности для поддержки этого типа правил.
> **Совместимость с разными версиями AdGuard.** Только AdGuard для Windows, Mac, Android имеют технические возможности для поддержки правила с модификатором `$app`.
<a id="redirect-modifier"></a>
#### **`redirect`**
@ -1025,7 +1023,7 @@ AdGuard может перенаправлять веб-запросы к лок
AdGuard использует тот же синтаксис правил фильтрации, что и uBlock Origin. Он совместим с модификатором `$rewrite=abp-resource` Adblock Plus.
`$redirect` это модификатор для [базовых правил](https://kb.adguard.com/ru/general/how-to-create-your-own-ad-filters#basic-rules), поэтому правила с ним поддерживают все остальные базовые модификаторы, такие как `$domain`, `$third-party`, `$script`, и т.д.
`$redirect` это модификатор для [базовых правил](#basic-rules), поэтому правила с ним поддерживают все остальные базовые модификаторы, такие как `$domain`, `$third-party`, `$script`, и т.д.
> Значение модификатора `$redirect` должно быть именем ресурса, который будет использован для переадресации.
@ -1048,13 +1046,13 @@ AdGuard использует тот же синтаксис правил фил
```
Это правило перенаправляет все запросы `example.org/test.mp4` к ресурсу `noopmp4-1s`.
> Больше информации о скриптлетах, редиректах и их использовании доступно [в этом разделе GitHub](https://github.com/AdguardTeam/Scriptlets#redirect-resources).
> Больше информации о редиректах и их использовании доступно [на GitHub](https://github.com/AdguardTeam/Scriptlets#redirect-resources).
> **Совместимость с различными версиями AdGuard.** Этот тип правил не поддерживается AdGuard для iOS и для Safari.
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$redirect` не поддерживается в AdGuard Content Blocker, AdGuard для iOS и для Safari.
<a id="redirect-rule-modifier"></a>
#### **`redirect-rule`**
По сути, это тот же `$redirect`, поскольку у него тоже есть свойства "перенаправления" и логика у них практически аналогичная. Разница в том, что `$redirect-rule` применяется только в случае, если целевой запрос заблокирован другим базовым правилом.
По сути, это тот же [`$redirect`](#redirect-modifier), поскольку у него тоже есть свойства "перенаправления" и логика у них практически аналогичная. Разница в том, что `$redirect-rule` применяется только в случае, если целевой запрос заблокирован другим базовым правилом.
> Отключение `$redirect-rule` работает точно так же, как для обычных правил `$redirect`. Даже более того, `@@||example.org^$redirect` будет отключать как правило `$redirect`, так и правило `$redirect-rule`.
@ -1067,11 +1065,13 @@ AdGuard использует тот же синтаксис правил фил
В этом случае только запросы к `example.org/script.js` будут перенаправлены. Все остальные запросы к `example.org` изменены не будут.
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$redirect-rule` не поддерживается в AdGuard Content Blocker, AdGuard для iOS и для Safari.
<a id="denyallow-modifier"></a>
#### **`denyallow`**
Модификатор `denyallow` позволяет избежать создания дополнительных правил, когда требуется отключить то или иное правило для определённого домена(-ов). Модификатор `denyallow` соответствует только целевым доменам, но не доменам реферера.
Модификатор `$denyallow` позволяет избежать создания дополнительных правил, когда требуется отключить то или иное правило для определённого домена(-ов). Модификатор `$denyallow` соответствует только целевым доменам, но не доменам реферера.
Добавление этого модификатора в правило равносильно исключению доменов при помощи паттерна правила либо при помощи добавления дополнительных правил-исключений. Чтобы указать несколько доменов в одном правиле, используйте символ `|` в качестве разделителя.
@ -1104,6 +1104,8 @@ AdGuard использует тот же синтаксис правил фил
@@||y.com$script,domain=a.com|b.com
```
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$denyallow` не поддерживаются в AdGuard Content Blocker.
<a id="noop-modifier"></a>
#### **`noop`**
@ -1116,7 +1118,7 @@ AdGuard использует тот же синтаксис правил фил
||example.com$replace=/bad/good/,___,~third-party
```
> **Совместимость с различными версиями AdGuard.** На данный момент доступен **только в девелоперских сборках**.
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `noop` не поддерживаются в AdGuard Content Blocker.
<a id="removeheader-modifier"></a>
#### **`$removeheader`**
@ -1215,8 +1217,7 @@ AdGuard использует тот же синтаксис правил фил
@@||example.org/path/$removeheader
```
> **Совместимость с различными версиями AdGuard.** На данный момент доступен **только в девелоперских сборках**.
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$removeheader` поддерживаются в AdGuard для Windows, Mac, Android, а также браузерными расширениями AdGuard для Chrome, Firefox, Edge.
<a id="non-basic-rules"></a>
# Другие правила
@ -1233,7 +1234,7 @@ AdGuard использует тот же синтаксис правил фил
Правила скрытия элементов предназначены, как это следует из их названия, для скрытия элементов веб-страниц. По сути это аналогично применению стиля `{ display: none; }` к выбранному элементу.
> Обратите внимание, что правила скрытия элементов работают по-разному и их приоритет меняется [в зависимости от платформы](https://kb.adguard.com/ru/general/how-to-create-your-own-ad-filters#cosmetic-rules-priority).
> Правила скрытия элементов работают по-разному и их приоритет меняется [в зависимости от платформы](#cosmetic-rules-priority).
<a id="elemhide-syntax"></a>
#### Синтаксис правил скрытия
@ -1248,13 +1249,13 @@ domains = [domain0, domain1[, ...[, domainN]]]
Если вы хотите ограничить область действия одним или более доменами, просто перечислите их через запятую. Например: `example.org,example.com##selector`.
> Обратите внимание, что это правило будет работать также на всех поддоменах `example.org` и `example.com`.
> Это правило будет работать также на всех поддоменах `example.org` и `example.com`.
Если вы хотите запретить действие правила на определенном домене, используйте символ `~` перед именем домена. Например: `~example.org##selector`.
Вы можете использовать оба подхода в одном правиле. Например, правило `example.org,~subdomain.example.org##domain` будет работать для домена `example.org` и всех его поддоменов, **кроме `subdomain.example.org`**.
> **Важно**. Правила скрытия не зависят друг от друга. Если в фильтре есть правило `example.org##selector`, и вы добавляете правило `~example.org##selector`, то оба этих правила будут применены независимо друг от друга.
> **Обратите внимание:** Правила скрытия не зависят друг от друга. Если в фильтре есть правило `example.org##selector`, и вы добавляете правило `~example.org##selector`, то оба этих правила будут применены независимо друг от друга.
<a id="elemhide-examples"></a>
#### Примеры правил скрытия
@ -1263,7 +1264,7 @@ domains = [domain0, domain1[, ...[, domainN]]]
* `example.com,example.org###adblock` — скроет элемент с атрибутом `id` равным `adblock` на доменах `example.com`, `example.org` и всех их поддоменах.
* `~example.com##.textad` — скроет элемент с классом `textad` на всех доменах, кроме `example.com` и всех его поддоменах.
> **Важно!** Safari не поддерживает одновременно разрешенные и запрещенные домены, поэтому правила вида `example.org,~foo.example.org##.textad` не действуют в AdGuard для Safari.
> **Ограничения:** Safari не поддерживает одновременно разрешенные и запрещенные домены, поэтому правила вида `example.org,~foo.example.org##.textad` не работают в AdGuard для Safari.
<a id="elemhide-exceptions"></a>
#### Исключения для правил скрытия
@ -1298,11 +1299,11 @@ example.com#@#.textad
Иногда недостаточно просто скрыть какой-либо элемент, чтобы заблокировать рекламу. Например, блокировка рекламного элемента может просто сломать верстку сайта. Для таких случаев AdGuard позволяет использовать гораздо более гибкие правила, чем обычные правила скрытия. По сути, с помощью таких правил вы можете добавить на страницу любой CSS-стиль.
> **Ограничения**. Запрещено использование стилей, которые могут приводить к загрузке каких-либо ресурсов. По сути это означает, что запрещено использование атрибутов типа `<url>`.
> **Ограничения.** Запрещено использование стилей, которые могут приводить к загрузке каких-либо ресурсов. По сути это означает, что запрещено использование атрибутов типа `<url>`.
> **Совместимость с различными версиями AdGuard.** Заметьте, что CSS-правила не поддерживаются AdGuard Content Blocker.
> **Совместимость с разными версиями AdGuard.** Правила CSS-стилей не поддерживаются в AdGuard Content Blocker.
> Обратите внимание, что правила CSS-стилей работают по-разному и их приоритет меняется [в зависимости от платформы](https://kb.adguard.com/ru/general/how-to-create-your-own-ad-filters#cosmetic-rules-priority).
> Правила CSS-стилей работают по-разному и их приоритет меняется [в зависимости от платформы](#cosmetic-rules-priority).
<a id="cosmetic-css-rules-syntax"></a>
#### Синтаксис
@ -1345,11 +1346,11 @@ example.com#@$#.textad { visibility: hidden; }
<a id="extended-css-selectors"></a>
### Расширенные CSS-селекторы
Возможностей CSS 3.0 не всегда хватает для блокировки рекламы. Чтобы решить эту проблему, AdGuard расширяет возможности CSS, добавляя поддержку новых псевдоэлементов. Для поддержки расширенных CSS-селекторов нами был разработан отдельный модуль [с открытым кодом](https://github.com/AdguardTeam/ExtendedCss).
Возможностей CSS 3.0 не всегда хватает для блокировки рекламы. Чтобы решить эту проблему, AdGuard расширяет возможности CSS, добавляя поддержку новых псевдоэлементов. Для поддержки расширенных CSS-селекторов мы разработали модуль [с открытым кодом](https://github.com/AdguardTeam/ExtendedCss).
> **Область применения**. Расширенные селекторы можно применять в любом косметическом правиле, будь то [правила скрытия](#cosmetic-elemhide-rules) или [правила CSS стилей](#cosmetic-css-rules).
> **Область применения**. Расширенные селекторы можно применять в любом косметическом правиле, будь то [правила скрытия](#cosmetic-elemhide-rules) или [правила CSS-стилей](#cosmetic-css-rules).
> **Совместимость с различными версиями AdGuard.** Заметьте, что CSS-правила не поддерживаются AdGuard Content Blocker.
> **Совместимость с разными версиями AdGuard.** Правила с расширенными CSS-селекторами не поддерживаются в AdGuard Content Blocker.
#### Синтаксис
@ -1358,9 +1359,9 @@ example.com#@$#.textad { visibility: hidden; }
Синтаксис расширенных CSS-правил:
* `#?#` — для скрытия элементов, `#@?#` — для исключений
* `#$?#` — для вставки CSS, `#@$?#` — для исключений
* `#$?#` — для CSS-стилей, `#@$?#` — для исключений
Мы **Крайне рекомендуем** использовать этим маркеры каждый раз, когда вы используете CSS-селектор.
Мы **крайне рекомендуем** использовать этим маркеры каждый раз, когда вы используете расширенный CSS-селектор.
##### Примеры
@ -1763,7 +1764,7 @@ div[class]:has(> a:not([id])) { remove: true; }
То, как применяются **правила скрытия элементов** и **правила CSS-стилей**, зависит от платформы.
**На AdGuard для Windows, Mac и Android** мы используем таблицу стилей, встроенную в страницу. Приоритет у косметических правил такой же, как и у любых других таблиц стилей CSS на сайтах. Но есть ограничение: [правила скрытия элементов](https://kb.adguard.com/ru/general/how-to-create-your-own-ad-filters#elemhide-rules) и [CSS-стили](https://kb.adguard.com/ru/general/how-to-create-your-own-ad-filters#cosmetic-css-rules) не могут обходить встроенные стили. В таких случаях рекомендуется использовать расширенные селекторы или HTML-фильтрацию.
**На AdGuard для Windows, Mac и Android** мы используем таблицу стилей, встроенную в страницу. Приоритет у косметических правил такой же, как и у любых других таблиц стилей CSS на сайтах. Но есть ограничение: [правила скрытия элементов](#elemhide-syntax) и [правила CSS-стилей](#cosmetic-css-rules) не могут обходить встроенные стили. В таких случаях рекомендуется использовать расширенные селекторы или HTML-фильтрацию.
**В браузерных расширениях AdGuard** используются так называемые "пользовательские таблицы стилей". Их приоритет выше, даже чем у встроенных стилей.
@ -1774,7 +1775,7 @@ div[class]:has(> a:not([id])) { remove: true; }
В большинстве случаев достаточно использовать базовые и косметические правила. Но иногда для фильтрации рекламы необходимо изменять HTML-код самой страницы до того, как он будет загружен браузером. Для того чтобы сделать это, применяются правила фильтрации HTML-контента. Они позволяют указать, какие HTML-элементы необходимо вырезать из страницы перед тем, как страница попадет в браузер.
> **Совместимость с различными версиями AdGuard.** Правила этого типа поддерживаются приложениями AdGuard для Windows, Mac, Android и расширением AdGuard для Firefox. Они не работают в расширениях для других браузеров, т.к. они не могут модифицировать контент на сетевом уровне.
> **Совместимость с разными версиями AdGuard.** Правила фильтрации HTML поддерживаются в AdGuard для Windows, Mac, Android и браузерным расширением AdGuard для Firefox. Они не работают в расширениях для других браузеров, потому что они не могут модифицировать содержимое страниц на сетевом уровне.
<a id="html-filtering-rules-syntax"></a>
### Синтаксис
@ -1897,9 +1898,9 @@ $@$script[tag-content="banner"]
AdGuard поддерживает специальный тип правил, позволяющий вставить любой javascript-код на страницы интернет-сайтов.
> **Ограничения**. Этот тип правил может быть использован **только в доверенных фильтрах**. В эту категорию попадают ваши собственные **Пользовательские правила**, и фильтры, которые создаются командой AdGuard.
> **Ограничения.** JavaScript-правила могут быть использованы **только в доверенных фильтрах**. В эту категорию попадают ваши **Пользовательские правила**, и фильтры, которые создаются командой AdGuard.
> **Совместимость с различными версиями AdGuard.** Javascript-правила не поддерживаются AdGuard Content Blocker.
> **Совместимость с разными версиями AdGuard.** Javascript-правила не поддерживаются в AdGuard Content Blocker.
Мы **крайне рекомендуем** использовать скриптлеты вместо Javascript-правил везде, где это возможно. JS-правила предназначены для помощи в процессе дебаггинга, но в качестве полноценного решения в долгосрочной перспективе следует использовать скриптлеты.
@ -1947,8 +1948,6 @@ example.com#@%#window.__gaq = undefined;
> AdGuard поддерживает множество различных скриптлетов. Чтобы добиться совместимости между различными блокировщиками, мы также поддерживаем синтаксис uBO и ABP.
> **Совместимость с различными версиями AdGuard.** Скриптлеты не поддерживаются AdGuard Content Blocker.
<a id="scriptlets-syntax"></a>
### Синтаксис
```
@ -1966,20 +1965,17 @@ example.org#%#//scriptlet("abort-on-property-read", "alert")
```
Это правило применится на страницах домена example.org (и его поддоменов) и выполнит скриптлет "abort-on-property-read" с параметром "alert".
```
[$app=com.apple.Safari]example.org#%#//scriptlet('prevent-setInterval', 'check', '!300')
```
Это правило применит соответствующий скриптлет только в браузере Safari на Mac.
Подробнее [об отладке скриптлетов](#debug-scriptlets).
Больше информации о скриптлетах можно найти [на GitHub](https://github.com/AdguardTeam/Scriptlets#scriptlets).
> Информация об отладке скриптлетов доступна в [этом разделе](#debug-scriptlets) статьи.
> **Совместимость с разными версиями AdGuard.** Скриптлеты не поддерживаются в AdGuard Content Blocker.
<a id="non-basic-rules-modifiers"></a>
## Модификаторы
Вы можете изменить поведение косметического правила, используя модификаторы, описанные ниже.
## Модификаторы для «не Базовых» правил
Поведение любого правила можно изменить, используя модификаторы, описанные ниже.
<a id="non-basic-rules-modifiers-syntax"></a>
### Синтаксис
@ -1996,24 +1992,27 @@ modifiers = modifier0[, modifier1[, ...[, modifierN]]]
В значениях модификаторов следующие символы должны быть экранированы: `[`, `]`, `,` и `\` (если он не используется для экранирования). Используйте `\`, чтобы экранировать их. Например, экранированная скобка выглядит так: `\]`.
<a id="non-basic-rules-modifiers-app"></a>
### app
Модификатор `app` ограничивает действие правила до конкретного приложения (или списка приложений). Поведение и синтаксис модификатора полностью совпадают с соответствующим [модификатором $app](https://kb.adguard.com/ru/general/how-to-create-your-own-ad-filters#app) для базовых правил.
### `app`
Примеры использования `app`:
Модификатор `$app` ограничивает действие правила до конкретного приложения или списка приложений. Поведение и синтаксис модификатора полностью совпадают с соответствующим [модификатором `$app` для базовых правил](#app-modifier).
#### Примеры `app`:
* `[$app=org.example.app]example.com##.textad` — скрывает `div` и заменяет его на класс `textad` на `example.com` и всех поддоменах в запросах, посланных из `org.example.app` приложения Android.
* `[$app=~org.example.app1|~org.example.app2]example.com##.textad` — скрывает `div` и заменяет его на класс `textad` на `example.com` и всех поддоменах в запросах, посланных из любого приложения кроме `org.example.app1` и `org.example.app2`.
* `[$app=com.apple.Safari]example.org#%#//scriptlet('prevent-setInterval', 'check', '!300')` — это правило применит соответствующий скриптлет только в браузере Safari на Mac.
* `[$app=org.example.app]#@#.textad` — отключит все правила `##.textad` для всех доменов при использовании приложения `org.example.app`.
> **Совместимость с различными версиями AdGuard.** Этот тип правил поддерживается AdGuard для Windows, Mac и Android. **На данный момент только в девелоперских сборках.**
> **Совместимость с разными версиями AdGuard.** Этот тип правил поддерживается AdGuard для Windows, Mac и Android. **На данный момент только в девелоперских сборках.**
<a id="non-basic-rules-modifiers-domain"></a>
### domain
Модификатор `domain` ограничивает область действия правила списком доменов (и их поддоменов).
Поведение и синтаксис модификатора полностью совпадают с соответствующим [модификатором $domain](https://kb.adguard.com/ru/general/how-to-create-your-own-ad-filters#domain) из базовых правил.
### `domain`
Примеры использования `domain`:
Модификатор `$domain` ограничивает область действия правила списком доменов и их поддоменов.
Поведение и синтаксис модификатора полностью совпадают с соответствующим [модификатором `$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` и его поддоменов.
@ -2025,9 +2024,10 @@ modifiers = modifier0[, modifier1[, ...[, modifierN]]]
Но правила, в которых используется смешанный стиль ограничения на домены, считаются некорректными. Так, например, правило `[$domain=example.org]example.com##.textad` будет отклонено.
<a id="non-basic-rules-modifiers-path"></a>
### path
Модификатор `path` ограничивает действие правила определенным местоположением или страницей на сайтах.
### `path`
Модификатор `$path` ограничивает действие правила определенным местоположением или страницей на сайтах.
#### Синтаксис
```
@ -2040,7 +2040,7 @@ path=pattern
> Модификатор `path` поддерживает регулярные выражения [таким же образом](#regexp-support), что и основные правила.
Примеры использования `path`:
#### Примеры `path`:
* `[$path=page.html]##.textad` — скрывает `div` с классом `textad` на `/page.html`, `/page.html?<query>`, `/sub/page.html` или `/another_page.html`
* `[$path=/page.html]##.textad` — скрывает `div` с классом `textad` на `/page.html`, `/page.html?<query>`, `/sub/page.html` любого домена, но не на `/another_page.html`
* `[$path=|/page.html]##.textad` — скрывает `div` с классом `textad` на `/page.html` или `/page.html?<query>` любого домена, но не на `/sub/page.html`
@ -2049,7 +2049,7 @@ path=pattern
* `[$domain=example.com,path=/page.html]##.textad` — скрывает `div` с классом `textad` на `page.html` домена `example.com` и всех его поддоменах, но не на `another_page.html`
* `[$path=/\\/(sub1|sub2)\\/page\\.html/]##.textad` — скрывает `div` с классом `textad` как на `/sub1/page.html`, так и `/sub2/page.html` любого домена (обратите внимание на [экранированные символы](#non-basic-rules-modifiers-syntax))
> **Совместимость с разными версиями AdGuard.** Правила с этим модификатором поддерживаются AdGuard для Windows, Mac, Android,а также браузерными расширениями AdGuard для Chrome, Firefox, Edge.
> **Совместимость с разными версиями AdGuard.** Правила с модификатором `$path` поддерживаются в AdGuard для Windows, Mac, Android, а также браузерными расширениями AdGuard для Chrome, Firefox, Edge.
### Редиректы
@ -2077,9 +2077,10 @@ AdGuard использует тот же синтаксис правил фил
```
Это правило перенаправляет все запросы к example.org/test.mp4 на ресурс с названием noopmp4-1s.
>Дополнительная информация о скриптлетах, редиректах и их использовании доступна в [соответствующем разделе на GitHub](https://github.com/AdguardTeam/Scriptlets#adguard-scriptlets-and-redirect-resources).
> Дополнительная информация о скриптлетах, редиректах и их использовании доступна [на GitHub](https://github.com/AdguardTeam/Scriptlets#adguard-scriptlets-and-redirect-resources).
> **Совместимость с различными версиями AdGuard.** Этот тип правил поддерживается AdGuard для Windows, Mac и Android. **На данный момент только в девелоперских сборках.**
> **Совместимость с разными версиями AdGuard.** Этот тип правил поддерживается AdGuard для Windows, Mac и Android. **На данный момент только в девелоперских сборках.**
<a id="for_maintainers"></a>
## Информация для разработчиков фильтров
@ -2269,14 +2270,14 @@ example.org#@#.adBanner
- полная: https://filters.adtidy.org/extension/chromium/filters/2.txt
- оптимизированная: https://filters.adtidy.org/extension/chromium/filters/2_optimized.txt
**Важно: Если вы хотите добавить правило, которое не должно удаляться при оптимизации, используйте хинт NOT_OPTIMIZED:**
**Если вы хотите добавить правило, которое не должно удаляться при оптимизации, используйте хинт `NOT_OPTIMIZED`:**
```
!+ NOT_OPTIMIZED
||example.org^
```
**А такое правило не будет оптимизировано только для ОС Android:**
**А такое правило не будет оптимизировано только для AdGuard для Android:**
```
!+ NOT_OPTIMIZED PLATFORM(android)
@ -2284,13 +2285,12 @@ example.org#@#.adBanner
```
<a id="platform_not_platform"></a>
#### PLATFORM и NOT_PLATFORM hints
Записи этого типа позволяют указывать системную платформу, для которой применяется правило. Ниже представлен список используемых платформ:
* `windows` — например, Базовый фильтр для Windows — [https://filters.adtidy.org/windows/filters/2.txt](https://filters.adtidy.org/windows/filters/2.txt)
* `mac` — например, Базовый фильтр для Mac — [https://filters.adtidy.org/mac_v2/filters/2.txt](https://filters.adtidy.org/mac_v2/filters/2.txt)
@ -2315,14 +2315,14 @@ example.org#@#.adBanner
Примеры:
Это правило будет действовать только для Windows, Mac и Android:
Это правило будет действовать только в AdGuard для Windows, Mac, Android:
```
!+ PLATFORM(windows,mac,android)
||example.org^
```
Это правило будет действовать для всех платформ за исключением расширения Safari, iOS, и Android:
Это правило будет действовать для всех платформ, кроме AdGuard для Safari, Android Content Blocker и AdGuard для iOS:
```
!+ NOT_PLATFORM(ext_safari, ext_android_cb, ios)
@ -2402,7 +2402,7 @@ ExtendedCss.query(selectorText) // returns an array of Elements matching selecto
<a id="debug-scriptlets"></a>
### Отладка скриптлетов
Если вы используете браузерное расширение AdGuard и хотите отладить [скриптлет-правило](https://kb.adguard.com/ru/general/how-to-create-your-own-ad-filters#scriptlets), вы можете получить дополнительную информацию, просто открыв Журнал фильтрации. В этом случае, скриптлеты переключатся в режим отладки и будут писать больше информации в браузерную консоль.
Если вы используете браузерное расширение AdGuard и хотите отладить [скриптлет-правило](#scriptlets), вы можете получить дополнительную информацию, просто открыв Журнал фильтрации. В этом случае, скриптлеты переключатся в режим отладки и будут писать больше информации в браузерную консоль.
Следующие скриптлеты разработаны специально для отладки: