Ir para o conteúdo principal

How to create your own ad filters

info

Neste artigo, explicamos como escrever regras de filtragem personalizadas para uso em produtos AdGuard. To test your rules, you can download the AdGuard app

A filter is a set of filtering rules applied to specific content, such as banners or popups. AdGuard has a list of standard filters created by our team. We constantly improve and update them, striving to meet the needs of most of our users.

At the same time, AdGuard allows you to create your own custom filters using the same types of rules that we have in our filters.

To describe the syntax of our filtering rules, we use Augmented BNF for Syntax Specifications, but we do not always strictly follow this specification.

info

Originally, the AdGuard's syntax was based on the syntax of Adblock Plus rules. Later, we extended it with new types of rules for better ad filtering. Some parts of this article about the rules common both to AdGuard and ABP were taken from the Adblock Plus guide on how to write filters.

Comments

Any line that starts with an exclamation mark is a comment. In the list of rules it is displayed in gray color. AdGuard will ignore this line, so you can write anything you want. Comments are usually placed above the rules and used to describe what a rule does.

Por exemplo:

! This is the comment. Below this line, there is an actual filtering rule.
||example.org^

Examples

Blocking by domain name

Blocking by domain name

This rule blocks:

  • http://example.org/ad1.gif
  • http://subdomain.example.org/ad1.gif
  • https://ads.example.org:8000/

This rule does not block:

  • http://ads.example.org.us/ad1.gif
  • http://example.com/redirect/http://ads.example.org/

By default, such rules do not work for document requests. This means that the ||example.org^ rule will block a request made to example.org when you try to navigate to this domain from another website, but if you type example.org into the address bar and try to navigate to it, the website will open. To block the document request, you will need to use a rule with the $document modifier: ||example.org^$document.

Blocking exact address

Blocking exact address

This rule blocks:

  • http://example.org/

This rule does not block:

  • https://example.org/banner/img

Basic rule modifiers

Filtering rules support numerous modifiers that allow you to fine-tune the rule behavior. Here is an example of a rule with some simple modifiers.

Basic rule modifiers

This rule blocks:

  • http://example.org/script.js if this script is loaded from example.com.

This rule does not block:

  • https://example.org/script.js if this script is loaded from example.org.
  • https://example.org/banner.png because it is not a script.

Unblocking an address

Unblocking an address

This rule unblocks:

  • http://example.org/banner.png even if there is a blocking rule for this address.

Blocking rules with $important modifier can override exceptions.

Unblocking an entire website

Unblocking an entire website

This rule unblocks

  • It disables all cosmetic rules on example.com.
  • It unblocks all requests sent from this website even if there is are blocking rules matching these requests.

Cosmetic rule

Cosmetic rule

Cosmetic rules are based on using a special language named CSS, which every browser understands. Basically, it adds a new CSS style to the website which purpose is to hide particular elements. You can learn more about CSS in general here.

AdGuard extends CSS and lets filters developers handle much more complicated cases. However, to use these extended rules, you need to be fluent in regular CSS.

Popular CSS selectors

NameCSS selectorDescription
ID selector#bannersMatches all elements with id attribute equal to banners.
ID selector
Class selector.bannersMatches all elements with class attribute containing banners.
Class selector
Attribute selectordiv[class="banners"]Matches all div elements with class attribute exactly equal to banners.
Attribute selector
Attribute substring selectordiv[class^="advert1"]Matches all div elements which class attribute starts with the advert1 string.
Attribute substring selector
Attribute substring selectordiv[class$="banners_ads"]Matches all div elements which class attribute ends with the banners_ads string.
Attribute substring selector
Attribute substring selectora[href^="http://example.com/"]Matches all links that are loaded from http://example.com/ domain.
Attribute substring selector
Attribute selectora[href="http://example.com/"]Matches all links to exactly the http://example.com/ address.
Attribute selector

Restrictions and limitations

Trusted filters

Some rules can be used only in trusted filters. This category includes:

Bloqueador de conteúdo do AdGuard

AdGuard Content Blocker is an extension for Samsung and Yandex browsers that can be installed from Google Play. Não deve ser confundido com o AdGuard para Android, que é totalmente funcional e só pode ser baixado a partir do nosso site. Infelizmente, as capacidades do Bloqueador de conteúdo AdGuard são limitadas pelas permissões dos navegadores, compatíveis apenas com uma sintaxe antiga de filtros do Adblock Plus:

Devido às limitações acima, o Bloqueador de conteúdo AdGuard não será mencionado nas notas de compatibilidade.

SafariConverterLib

O Safari Converter tem como objetivo suportar a sintaxe das regras de filtragem do AdGuard o máximo possível, mas ainda existem limitações e deficiências difíceis de superar.

Regras básicas (de rede)

O conversor Safari suporta um subconjunto substancial de regras básicas e certamente suporta os tipos mais importantes dessas regras.

Suporte com limitações
  • As regras de expressão regular são limitadas ao subconjunto de regex que é compatível com o Safari.

  • $domain - o modificador de domínio é compatível com várias limitações.

    • É impossível misturar domínios permitidos e não permitidos (como $domain=example.org|~sub.example.org). Por favor, dê um upvote para a solicitação de funcionalidade para que o WebKit remova esta limitação.
    • "Any TLD" (ou seja, domain.*) não é totalmente suportado. Na implementação atual, o conversor simplesmente substitui .* pelos 100 TLDs mais populares. Esta implementação será aprimorada no futuro.
    • O uso de expressões regulares em $domain não é compatível, mas também será melhorado no futuro.
  • $denyallow - este modificador é suportado através da conversão da regra $denyallow para um conjunto de regras (uma regra de bloqueio + várias regras de desbloqueio).

    Devido a essa limitação, $denyallow é permitido apenas quando a regra também possui o modificador $domain.

    • A regra genérica *$denyallow=x.com,image,domain=a.com será convertida para:

      *$image,domain=a.com
      @@||x.com$image,domain=a.com
    • A regra /banner.png$image,denyallow=test1.com|test2.com,domain=example.org será convertida para:

      /banner.png$image,domain=example.org
      @@||test1.com/banner.png$image,domain=example.org
      @@||test1.com/*/banner.png$image,domain=example.org
      @@||test2.com/banner.png$image,domain=example.org
      @@||test2.com/*/banner.png$image,domain=example.org
    • A regra sem $domain não é suportada: $denyallow=a.com|b.com.

  • $popup - as regras de popup são compatíveis, mas são basicamente as mesmas que as regras de $document de bloqueio e não tentarão fechar a aba.

  • As regras de exceção (@@) desativam a filtragem cosmética em domínios correspondentes.

    As regras de exceção no Safari dependem do tipo de regra ignore-previous-rules, então, para que funcione, precisamos ordenar as regras em uma ordem específica. As regras de exceção sem modificadores são colocadas no final da lista e, portanto, desativam não apenas o bloqueio de URL, mas também as regras cosméticas.

    Essa limitação pode ser removida se #70 for implementado.

  • $urlblock, $genericblock é basicamente o mesmo que $document, ou seja, desativa todos os tipos de filtragem em sites.

    Estas limitações podem ser removidas quando #69 e #71 são implementados.

  • $content não faz sentido no caso do Safari, uma vez que as regras de filtragem HTML não são compatíveis, então está lá apenas por razões de compatibilidade. As regras com $content estão limitadas ao tipo de recurso documento.

  • $specifichide é implementado escaneando as regras de esconder elementos existentes e removendo o domínio alvo de sua matriz if-domain.

    • As regras de $specifichide DEVEM ter como alvo um domínio, ou seja, devem ser assim: ||example.org^$specifichide. Regras com padrões mais específicos serão descartadas, ou seja, ||example.org/path$specifichide não será suportado.
    • $specifichide regras cobrem apenas regras que visam o mesmo domínio que a regra em si, subdomínios são ignorados. I.e. a regra @@||example.org^$specifichide irá desativar example.org##.banner, mas irá ignorar sub.example.org##.banner. This limitation may be lifted if #72 is implemented.
  • Os modificadores urlblock, genericblock, generichide, elemhide, specifichide e jsinject podem ser usados apenas como modificador único em uma regra. Essa limitação pode ser removida no futuro: #73.

  • $websocket (suporte total a partir do Safari 15).

  • $ping (totalmente suportado a partir do Safari 14).

Não compatível
  • $app
  • $header
  • $method
  • $strict-first-party (a ser compatível no futuro: #64)
  • $strict-third-party (a ser compatível no futuro: #65)
  • $to (a ser compatível no futuro: #60)
  • $extension
  • $stealth
  • $cookie (suporte parcial no futuro: #54)
  • $csp
  • $hls
  • $inline-script
  • $inline-font
  • $jsonprune
  • $xmlprune
  • $network
  • $permissions
  • $redirect
  • $redirect-rule
  • $referrerpolicy
  • $removeheader
  • $removeparam
  • $replace
  • $urltransform

Regras cosméticas

O Safari Converter suporta a maioria das regras cosméticas, embora apenas as regras de ocultação de elementos com seletores CSS básicos sejam suportadas nativamente via bloqueio de conteúdo do Safari; tudo o mais precisa ser interpretado por uma extensão adicional.

Limitações das regras de cosméticos
  • Specifying domains is subject to the same limitations as the $domain modifier of basic rules.

  • Modificadores de regras não básicas são suportados com algumas limitações:

    • $domain - as mesmas limitações que em qualquer outro lugar.
    • $path - suportado, mas se você usar expressões regulares, elas serão limitadas ao subconjunto de expressão regular que é compatível com o Safari.
    • $url - a ser compatível no futuro: #68

Regras de script/scriptlet

O Safari Converter oferece suporte completo tanto às regras de script quanto às regras de scriptlet. No entanto, essas regras só podem ser interpretadas por uma extensão separada.

perigo

For scriptlet rules, it is very important that they are run as early as possible when the page loads. The reason for that is that it's important to run them before the page scripts. Infelizmente, com o Safari sempre haverá um pequeno atraso que pode diminuir a qualidade do bloqueio.

Regras de filtragem HTML

Regras de filtragem HTML não são compatíveis e não o serão no futuro. Infelizmente, Safari não fornece as capacidades técnicas necessárias para implementá-las.

Basic rules

The most simple rules are so-called Basic rules. Elas são usadas para bloquear solicitações a URLs específicas. Or to unblock it, if there is a special marker "@@" at the beginning of the rule. The basic principle for this type of rules is quite simple: you have to specify the address and additional parameters that limit or expand the rule scope.

Sub-requests

Regras básicas para bloquear solicitações são aplicadas somente a sub-solicitações. Isso significa que eles não bloquearão o carregamento da página, a menos que seja especificado com um modificador $document.

Status da resposta

O navegador detecta uma solicitação bloqueada como concluída com um erro.

Rule length

Regras mais curtas que 4 caracteres são consideradas incorretas e serão ignoradas.

Sintaxe de regras básica

      rule = ["@@"] pattern [ "$" modifiers ]
modifiers = [modifier0, modifier1[, ...[, modifierN]]]
  • pattern — uma máscara de endereço. Cada URL de solicitação é agrupada a esta máscara. No modelo, você também pode usar os caracteres especiais descritos abaixo. Observe que o AdGuard corta URLs para um comprimento de 4096 caracteres a fim de acelerar a correspondência e evitar problemas com URLs ridiculamente longas.
  • @@ — a marker that is used in rules of exception. Para desativar a filtragem de uma solicitação, inicie sua regra com este marcador.
  • modifiers — parâmetros que "esclarecem" a regra básica. Alguns deles limitam o escopo da regra e outros podem mudar completamente a forma como ela funciona.

Special characters

  • * — um caractere wildcard. It is used to represent any set of characters. Isso também pode ser uma string vazia ou uma string de qualquer tamanho.
  • || — uma indicação para aplicar a regra ao domínio especificado e seus subdomínios. Com este caractere, você não precisa especificar um protocolo ou subdomínio na máscara de endereço. Isso significa que || representa http://*., https://*., ws://*., wss://*. ao mesmo tempo.
  • ^ — uma marca de caractere separador. O caractere separador pode ser qualquer caractere, mas não uma letra, um dígito ou um dos seguintes: _ - . %. Neste exemplo, os caracteres separadores estão destacados em negrito: http://example.com/?t=1&t2=t3. The end of the address is also accepted as separator.
  • | — um ponteiro para o início ou o fim do endereço. O valor depende do posicionamento do caractere na máscara. Por exemplo, uma regra swf| corresponde a http://example.com/annoyingflash.swf, mas não a http://example.com/swf/index.html. |http://exemplo.org corresponde a http://exemplo.org, mas não a http://dominio.com?url=http://exemplo.org.
nota

|, ||, ^ só podem ser usados com regras que tenham um padrão de URL. Por exemplo, ||example.com##.advert está incorreto e será ignorado pelo bloqueador.

Visual representation

Recomendamos também que você se familiarize com o cheatsheet de filtros do Adblock Plus, para uma melhor compreensão de como tais regras devem ser feitas.

Regular expressions support

Se desejar ainda mais flexibilidade na criação de regras, você pode usar expressões regulares em vez de uma máscara simplificada padrão com caracteres especiais.

Performance

As regras com expressões regulares funcionam mais lentamente, portanto, é recomendado evitá-las ou limitar seu escopo a domínios específicos.

Se você quiser um bloqueador para determinar uma expressão regular, o pattern deve ficar assim:

pattern = "/" regexp "/"

For example, /banner\d+/$third-party this rule will apply the regular expression banner\d+ to all third-party requests. Uma regra de exclusão com expressão regular é assim: @@/banner\d+/.

Compatibility

O AdGuard para Safari e o AdGuard para iOS não suportam completamente expressões regulares por causa das restrições da API de Bloqueio de Conteúdo (procure pela seção "O formato da expressão regular").

Suporte a Wildcard para TLD (domínios de nível superior)

Os caracteres wildcard são compatíveis para TLDs dos domínios em padrões de cosméticos, filtragem HTML e regras JavaScript.

Para regras cosméticas, por exemplo, example.*##.banner, múltiplos domínios são correspondidos devido à parte .*, ou seja, example.com, sub.example.net, example.co.uk, etc.

Para regras básicas, a lógica descrita é aplicável apenas para os domínios especificados no modificador $domain, por exemplo, ||*/banners/*$image,domain=example.*.

Compatibility

Nas regras com wildcard do AdGuard para Windows, Android, Mac e da Extensão do AdGuard para navegador .* correspondem a qualquer sufixo público (ou eTLD). Mas para AdGuard para Safari e iOS a lista suportada de domínios de nível superior é limitada devido às limitações do Safari.

Regras com wildcard para TLD não são compatíveis com o Bloqueador de conteúdo do AdGuard.

Basic rule examples

  • ||example.com/ads/* — uma regra simples, que corresponde a endereços como http://example.com/ads/banner.jpg e até http://subdomain.example.com/ads/otherbanner.jpg.

  • ||example.org^$third-party — esta regra bloqueia solicitações de terceiros para example.org e seus subdomínios.

  • @@||example.com$document — regra de exceção geral. Desativa completamente a filtragem para example.com e todos os subdomínios. Há uma série de modificadores que podem ser usados nas regras de exceção. Para mais detalhes, siga o link abaixo.

Basic rule modifiers

nota

Os recursos descritos nesta seção são destinados a usuários experientes. Eles estendem as capacidades das "Regras básicas", mas para usá-las, você precisa ter um entendimento básico de como seu navegador funciona.

Você pode alterar o comportamento de uma "regra básica" adicionando modificadores. Os modificadores devem estar localizados no final da regra após o caractere $ e ser separados por vírgulas.

Example:

||domain.com^$popup,third-party

Basic modifiers

Os seguintes modificadores são os mais simples e frequentemente usados. Basicamente, eles apenas limitam o escopo da aplicação das regras.

Modificador \ ProdutosAplicativos do CoreLibsAdGuard for ChromiumAdGuard for Chrome MV3AdGuard for FirefoxAdGuard para iOSAdGuard para SafariBloqueador de conteúdo do AdGuard
$app
$denyallow
$domain*[1]*[1]*[1]
$header*[2]*[2]
$important
$match-case
$method
$popup*[3]*[3]*[3]*[3]
$strict-first-party
$strict-third-party
$third-party
$to
nota
  • ✅ — fully supported
  • ✅ * — supported, but reliability may vary or limitations may occur; check the modifier description for more details
  • ⏳ — recurso que está planejado para ser implementado, mas ainda não está disponível em nenhum produto
  • ❌ — not supported

$app

Este modificador permite que você restrinja a abrangência da regra a um aplicativo específico (ou uma lista de aplicativos). Isso pode não ser tão importante no Windows e no Mac, mas é muito importante em dispositivos móveis onde algumas das regras de filtragem devem ser específicas do aplicativo.

  • Android — use o nome do pacote do aplicativo, e.g. org.example.app.
  • Windows — use o nome do processo, por exemplo, chrome.exe.
  • Mac — use o ID do pacote ou o nome do processo, por exemplo, com.google.Chrome.

Para Mac, você pode descobrir o ID do pacote ou o nome do processo do aplicativo visualizando os detalhes da solicitação no registro de filtragem.

Examples

  • ||baddomain.com^$app=org.example.app — uma regra para bloquear solicitações que correspondem à máscara especificada e são enviadas do aplicativo org.example.app para Android.
  • ||baddomain.com^$app=org.example.app1|org.example.app2 — a mesma regra, mas funciona para os aplicativos org.example.app1 e org.example.app2.

Se você quer que a regra não seja aplicada a certos aplicativos, comece o nome do aplicativo com o sinal ~.

  • ||baddomain.com^$app=~org.example.app — uma regra para bloquear solicitações que correspondem à máscara especificada e são enviadas de qualquer aplicativo, exceto o org.example.app.
  • ||baddomain.com^$app=~org.example.app1|~org.example.app2 — o mesmo que acima, mas agora dois aplicativos estão excluídos: org.example.app1 e org.example.app2.
Restrictions

Os aplicativos no valor do modificador não podem ter um wildcard, por exemplo, $app=com.*.music. As regras com tal modificador são consideradas inválidas.

Compatibility
  • Apenas o AdGuard para Windows, Android é tecnicamente capaz de usar regras com o modificador $app.
  • On Windows the process name is case-insensitive starting with AdGuard for Windows with CoreLibs v1.12 or later.

$denyallow

O modificador $denyallow permite evitar a criação de regras adicionais quando é necessário desativar uma determinada regra para domínios específicos. $denyallow combina apenas com domínios de destino e não com domínios de referência.

Adicionar esse modificador a uma regra é equivalente a excluir os domínios pelo padrão de correspondência da regra ou a adicionar as regras de exclusão correspondentes. Para adicionar vários domínios a uma regra, use o caractere | como separador.

Examples

This rule:

*$script,domain=a.com|b.com,denyallow=x.com|y.com

is equivalent to this one:

/^(?!.*(x.com|y.com)).*$/$script,domain=a.com|b.com

ou à combinação desses três:

*$script,domain=a.com|b.com
@@||x.com$script,domain=a.com|b.com
@@||y.com$script,domain=a.com|b.com
Restrictions
  • O padrão de correspondência da regra não pode direcionar a nenhum domínio específico, por exemplo, não pode começar com ||.
  • Os domínios no valor do modificador não podem ser negados, por exemplo, $denyallow=~x.com, ou ter um TLD wildcard, por exemplo, $denyallow=x.*, ou ser uma expressão regular, por exemplo, $denyallow=/\.(com\|org)/.
  • $denyallow não pode ser usado junto com $to. Pode ser expresso com $to invertido: $denyallow=a.com|b.com é equivalente a $to=~a.com|~b.com.

As regras que violam essas restrições são consideradas inválidas.

Compatibility

Regras com o modificador $denyallow não são suportadas pelo AdGuard para iOS, Safari e Bloqueador de conteúdo do AdGuard.

$domain

$domain limita o escopo da regra às solicitações feitas a partir dos domínios especificados e seus subdomínios (conforme indicado pelo cabeçalho HTTP Referer).

Syntax

O modificador é uma lista de uma ou mais expressões separadas pelo símbolo |, cada uma das quais é correspondida a um domínio de uma maneira particular dependendo do seu tipo (veja abaixo).

domains = ["~"] entry_0 ["|" ["~"] entry_1 ["|" ["~"]entry_2 ["|" ... ["|" ["~"]entry_N]]]]
entry_i = ( regular_domain / any_tld_domain / regexp )
  • regular_domain — a regular domain name (domain.com). Corresponds the specified domain and its subdomains. It is matched lexicographically.
  • any_tld_domain — a domain name ending with a wildcard character as a public suffix, e.g. for example.* it is co.uk in example.co.uk. Corresponds to the specified domain and its subdomains with any public suffix. It is matched lexicographically.
  • regexp — a regular expression, starts and ends with /. The pattern works the same way as in the basic URL rules, but the characters /, $, ,, and | must be escaped with \.
info

Rules with $domain modifier as regular_domain are supported by all AdGuard products.

Examples

Just $domain:

  • ||baddomain.com^$domain=example.org bloqueia solicitações que correspondem à máscara especificada e são enviadas do domínio example.org ou seus subdomínios.
  • ||baddomain.com^$domain=example.org|example.com — a mesma regra, mas funciona para ambos example.org e example.com.

If you want the rule not to be applied to certain domains, start a domain name with ~ sign.

$domain and negation ~:

  • ||baddomain.com^$domain=example.org bloqueia solicitações que correspondem à máscara especificada e são enviadas do domínio example.org ou seus subdomínios.
  • ||baddomain.com^$domain=example.org|example.com — a mesma regra, mas funciona para ambos example.org e example.com.
  • ||baddomain.com^$domain=~example.org bloqueia solicitações que correspondem ao padrão enviado de qualquer domínio, exceto example.org e seus subdomínios.
  • ||baddomain.com^$domain=example.org|~foo.example.org bloqueia solicitações enviadas de example.org e seus subdomínios, exceto o subdomínio foo.example.org.
  • ||baddomain.com^$domain=/(^\|.+\.)example\.(com\|org)\$/ bloqueia solicitações enviadas dos domínios example.org e example.com e todos os seus subdomínios.
  • ||baddomain.com^$domain=~a.com|~b.*|~/(^\|.+\.)c\.(com\|org)\$/ blocks requests sent from any domains, except a.com, b with any public suffix (b.com, b.co.uk, etc.), c.com, c.org, and their subdomains.

$domain modifier matching target domain:

In some cases the $domain modifier can match not only the referrer domain, but also the target domain. This happens when all the following conditions are met:

  1. The request has the document content type
  2. The rule pattern does not match any particular domains
  3. The rule pattern does not contain regular expressions
  4. O modificador $domain contém apenas domínios excluídos, por exemplo, $domain=~example.org|~example.com

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 are not met but the rule contains $cookie or $csp 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 will not be applied even if the target domain also matches the rule. This affects rules with $cookie and $csp modifiers, too.

Examples

  • *$cookie,domain=example.org|example.com bloqueará cookies para todas as solicitações para e de example.org e example.com.
  • *$document,domain=example.org|example.com bloqueará todas as solicitações para e a partir de example.org e example.com.

Nos exemplos a seguir, implica-se que as solicitações são enviadas de http://example.org/page (o referenciador) e a URL de destino é http://targetdomain.com/page.

  • page$domínio=example.org será combinado, pois corresponde ao domínio do referenciador.
  • page$domain=targetdomain.com will be matched, as it matches the target domain and satisfies all requirements mentioned above.
  • ||*page$domain=targetdomain.com will not be matched, as the pattern ||*page may match specific domains, e.g. example.page.
  • ||*page$domain=targetdomain.com,cookie will be matched because the rule contains $cookie modifier despite the pattern ||*page may match specific domains.
  • /banner\d+/$domain=targetdomain.com will not be matched as it contains a regular expression.
  • page$domínio=targetdomain.com|~example.org não será correspondente porque o domínio de referência foi explicitamente excluído.
$domain modifier limitations
Limitations

In AdGuard for Chrome MV3, regexp and any_tld_domain entries are not supported.

Restrictions

O Safari não permite o uso simultâneo de domínios permitidos e não permitidos, portanto, regras como ||baddomain.com^$domain=example.org|~foo.example.org não funcionarão no AdGuard para iOS e no AdGuard para Safari.

Compatibility

Rules with regular expressions in the $domain modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.11 or later, and AdGuard Browser Extension with TSUrlFilter v3.0.0 or later.

In AdGuard for Windows, Mac and Android with CoreLibs v1.12 or later the $domain modifier can be alternatively spelled as $from.

$header

The $header modifier allows matching the HTTP response having a specific header with (optionally) a specific value.

Syntax

$header "=" h_name [":" h_value]
h_value = string / regexp

where:

  • h_name — required, an HTTP header name. It is matched case-insensitively.
  • h_value — optional, an HTTP header value matching expression, it may be one of the following:
    • string — a sequence of characters. It is matched against the header value lexicographically;
    • regexp — a regular expression, starts and ends with /. The pattern works the same way as in the basic URL rules, but the characters /, $ and , must be escaped with \.

The modifier part, ":" h_value, may be omitted. In that case, the modifier matches the header name only.

Examples

  • ||example.com^$header=set-cookie:foo blocks requests whose responses have the Set-Cookie header with the value matching foo literally.
  • ||example.com^$header=set-cookie blocks requests whose responses have the Set-Cookie header with any value.
  • @@||example.com^$header=set-cookie:/foo\, bar\$/ unblocks requests whose responses have the Set-Cookie header with value matching the foo, bar$ regular expression.
  • @@||example.com^$header=set-cookie unblocks requests whose responses have a Set-Cookie header with any value.
$header modifier limitations
Restrictions
  1. The $header modifier can be matched only when headers are received. So if the request is blocked or redirected at an earlier stage, the modifier cannot be applied.
  2. In AdGuard Browser Extension, the $header modifier is only compatible with $csp, $removeheader, $important, and $badfilter.
Compatibility

Rules with the $header modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.11 or later, and AdGuard Browser Extension with TSUrlFilter v3.0.0 or later.

$important

The $important modifier applied to a rule increases its priority over rules without the identical modifier. Even over basic exception rules.

Go to rules priorities for more details.

Examples

! a regra de bloqueio bloqueará todas as solicitações apesar da regra de exceção
||example.org^$important
@@||example.org^
! se a regra de exceção também tiver o modificador `$important`, ela prevalecerá e as solicitações não serão bloqueadas
||example.org^$important
@@||example.org^$important

$match-case

This modifier defines a rule which applies only to addresses that match the case. Default rules are case-insensitive.

Examples

  • */BannerAd.gif$match-case — this rule will block http://example.com/BannerAd.gif, but not http://example.com/bannerad.gif.
Compatibility

Rules with the $match-case are supported by AdGuard for iOS and AdGuard for Safari with SafariConverterLib v2.0.43 or later.

All other products already support this modifier.

$method

This modifier limits the rule scope to requests that use the specified set of HTTP methods. Negated methods are allowed. The methods must be specified in all lowercase characters, but are matched case-insensitively. To add multiple methods to one rule, use the vertical bar | as a separator.

Examples

  • ||evil.com^$method=get|head blocks only GET and HEAD requests to evil.com.
  • ||evil.com^$method=~post|~put blocks any requests to evil.com except POST or PUT.
  • @@||evil.com$method=get unblocks only GET requests to evil.com.
  • @@||evil.com$method=~post unblocks any requests to evil.com except POST.
Restrictions

Rules with mixed negated and not negated values are considered invalid. So, for example, the rule ||evil.com^$method=get|~head will be ignored.

Compatibility

Rules with $method modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.12 or later, and AdGuard Browser Extension for Chrome, Firefox, and Edge with TSUrlFilter v2.1.1 or later.

AdGuard will try to close the browser tab with any address that matches a blocking rule with this modifier. Please note that not all the tabs can be closed.

Examples

  • ||domain.com^$popup — if you try to go to http://domain.com/ from any page in the browser, a new tab in which specified site has to be opened will be closed by this rule.
Limitations
  1. The $popup modifier works best in AdGuard Browser Extension for Chromium-based browsers and Firefox.
  2. In AdGuard for Chrome MV3 rules with the $popup modifier would not work, so we disable converting them to declarative rules. We will try to use them only in our TSUrlFilter engine and close new tabs programmatically.
  3. In AdGuard for iOS and AdGuard for Safari, $popup rules simply block the page right away.
  4. In AdGuard for Windows, AdGuard for Mac, and AdGuard for Android, the $popup modifier may not detect a popup in some cases and it will not be blocked. The $popup modifier applies the document content type with a special flag which is passed to a blocking page. Blocking page itself can do some checks and close the window if it is really a popup. Otherwise, page should be loaded. It can be combined with other request type modifiers, such as $third-party, $strict-third-party, $strict-first-party, and $important.
Compatibility

Rules with the $popup modifier are not supported by AdGuard Content Blocker.

$strict-first-party

Works the same as the $~third-party modifier, but only treats the request as first-party if the referrer and origin have exactly the same hostname.

Examples

  • domain.com$strict-first-party' — this rule applies only to domain.com. For example, a request from domain.com to http://domain.com/icon.ico is a first-party request. A request from sub.domain.com to http://domain.com/icon.ico is treated as a third-party one (as opposed to the $~third-party modifier).
nota

You can use a shorter name (alias) instead of using the full modifier name: $strict1p.

Compatibility

Rules with the $strict-first-party modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.16 or later.

$strict-third-party

Works the same as the $third-party modifier but also treats requests from the domain to its subdomains and vice versa as third-party requests.

Examples

  • ||domain.com^$strict-third-party — this rule applies to all domains except domain.com. An example of a third-party request: http://sub.domain.com/banner.jpg (as opposed to the $third-party modifier).
nota

You can use a shorter name (alias) instead of using the full modifier name: $strict3p.

Compatibility

Rules with the $strict-third-party modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.16 or later.

$third-party

A restriction on third-party and custom requests. A third-party request is a request from an external domain. Por exemplo, uma solicitação para example.org de domain.com é uma solicitação de terceiros.

nota

To be considered as such, a third-party request should meet one of the following conditions:

  1. Its referrer is not a subdomain of the target domain or vice versa. Por exemplo, uma solicitação para subdomain.example.org de example.org não é uma solicitação de terceiros
  2. Its Sec-Fetch-Site header is set to cross-site

Examples

$third-party:

  • ||domain.com^$third-party — this rule applies to all domains, except domain.com and its subdomains. Um exemplo de uma solicitação de terceiros: http://example.org/banner.jpg.

If there is a $~third-party modifier, the rule is only applied to the requests that are not from third parties. Which means, they have to be sent from the same domain.

$~third-party:

  • ||domain.com$~third-party — this rule is applied exclusively to domain.com. Example of a non third-party request: http://domain.com/icon.ico.
nota

You may use a shorter name (alias) instead of using the full modifier name: $3p.

$to

$to limits the rule scope to requests made to the specified domains and their subdomains. Para adicionar vários domínios a uma regra, use o caractere | como separador.

Examples

  • /ads$to=evil.com|evil.org blocks any request to evil.com or evil.org and their subdomains with a path matching /ads.
  • /ads$to=~not.evil.com|evil.com blocks any request to evil.com and its subdomains, with a path matching /ads, except requests to not.evil.com and its subdomains.
  • /ads$to=~good.com|~good.org blocks any request with a path matching /ads, except requests to good.com or good.org and their subdomains.
Restrictions

$denyallow cannot be used together with $to. Pode ser expresso com $to invertido: $denyallow=a.com|b.com é equivalente a $to=~a.com|~b.com.

Compatibility

Rules with the $to modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.12 or later, and AdGuard Browser Extension with TSUrlFilter v2.1.3 or later.

Modificadores do tipo Conteúdo

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

There is a big difference in how AdGuard determines the content type on different platforms. For AdGuard Browser Extension, content type for every request is provided by the browser. AdGuard for Windows, Mac, and Android use the following method: first, the apps 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.

Examples of content-type modifiers

  • ||example.org^$image — corresponde a todas as imagens de example.org.
  • ||example.org^$script,stylesheet — corresponde a todos os scripts e estilos de example.org.
  • ||example.org^$~image,~script,~stylesheet — corresponde a todas as solicitações para exemplo.org exceto para as imagens, scripts e folhas de estilo.
Modificador \ ProdutosAplicativos do CoreLibsAdGuard for ChromiumAdGuard for Chrome MV3AdGuard for FirefoxAdGuard para iOSAdGuard para SafariBloqueador de conteúdo do AdGuard
$document
$font
$image
$media
$object
$other
$ping*[1]
$script
$stylesheet
$subdocument*[2]
$websocket*[3]*[3]
$xmlhttprequest
$webrtc 🚫
$object-subrequest 🚫
nota
  • ✅ — fully supported
  • ✅ * — supported, but reliability may vary or limitations may occur; check the modifier description for more details
  • ❌ — not supported
  • 🚫 — removed and no longer supported

$document

The rule corresponds to the main frame document requests, i.e. HTML documents that are loaded in the browser tab. It does not match iframes, there is a $subdocument modifier for these.

By default, AdGuard does not block the requests that are loaded in the browser tab (e.g. "main frame bypass"). The idea is not to prevent pages from loading as the user clearly indicated that they want this page to be loaded. However, if the $document modifier is specified explicitly, AdGuard does not use that logic and prevents the page load. Instead, it responds with a "blocking page".

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, $extension modifiers simultaneously.

Examples

  • @@||example.com^$document completely disables filtering on all pages at example.com and all subdomains.

  • ||example.com^$document blocks HTML document request to example.com with a blocking page.

  • ||example.com^$document,redirect=noopframe redirects HTML document request to example.com to an empty html document.

  • ||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.

nota

You may use a shorter name (alias) instead of using the full modifier name: $doc.

$font

The rule corresponds to requests for fonts, e.g. .woff filename extension.

$image

The rule corresponds to images requests.

$media

The rule corresponds to requests for media files — music and video, e.g. .mp4 files.

$object

The rule corresponds to browser plugins resources, e.g. Java or Flash.

Compatibility

Rules with $object modifier are not supported by AdGuard for Safari and AdGuard for iOS.

$other

The rule applies to requests for which the type has not been determined or does not match the types listed above.

$ping

The rule corresponds to requests caused by either navigator.sendBeacon() or the ping attribute on links.

$ping modifier limitations
Limitations

AdGuard for Windows, Mac, and Android often cannot accurately detect navigator.sendBeacon(). Using $ping is not recommended in the filter lists that are supposed to be used by CoreLibs-based AdGuard products.

Compatibility

Rules with $ping modifier are not supported by AdGuard for Safari and AdGuard for iOS.

$script

The rule corresponds to script requests, e.g. JavaScript, VBScript.

$stylesheet

The rule corresponds to CSS files requests.

nota

You may use a shorter name (alias) instead of using the full modifier name: $css.

$subdocument

The rule corresponds to requests for built-in pages — HTML tags frame and iframe.

Examples

  • ||example.com^$subdocument blocks built-in page requests (frame and iframe) to example.com and all its subdomains anywhere.
  • ||example.com^$subdocument,domain=domain.com blocks built-in page requests (frame и iframe) to example.com (and its subdomains) from domain.com and all its subdomains.
nota

You may use a shorter name (alias) instead of using the full modifier name: $frame.

$subdocument modifier limitations
Limitations

In AdGuard for Windows, Mac, and Android subdocuments are being detected by the Sec-Fetch-Dest header if it is present. Otherwise, some main pages may be treated as subdocuments.

Compatibility

Rules with $subdocument modifier are not supported by AdGuard Content Blocker.

$websocket

The rule applies only to WebSocket connections.

$websocket modifier limitations
Limitations

For AdGuard for Safari and AdGuard for iOS, it is supported on devices with macOS Monterey (version 12) and iOS 16 or higher respectively.

Compatibility

$websocket modifier is supported in all AdGuard products except AdGuard Content Blocker.

$xmlhttprequest

The rule applies only to ajax requests (requests sent via the JavaScript object XMLHttpRequest).

nota

You may use a shorter name (alias) instead of using the full modifier name: $xhr.

Compatibility

AdGuard for Windows, Mac, Android when filtering older browsers cannot accurately detect this type and sometimes detects it as $other or $script. They can only reliably detect this content type when filtering modern browsers that support Fetch metadata request headers.

$object-subrequest (removed)

Removal notice

$object-subrequest modifier is removed and is no longer supported. Rules with it are considered as invalid. The rule corresponds to requests by browser plugins (it is usually Flash).

$webrtc (removed)

Removal notice

This modifier is removed and is no longer supported. Rules with it are considered as invalid. If you need to suppress WebRTC, consider using the nowebrtc scriptlet.

The rule applies only to WebRTC connections.

Examples

  • ||example.com^$webrtc,domain=example.org bloqueia as conexões webRTC para example.com a partir de example.org.
  • @@*$webrtc,domain=example.org desativa o wrapper RTC para example.org.

Exception rules modifiers

Exception rules disable the other basic rules for the addresses to which they correspond. They begin with a @@ mark. All the basic modifiers listed above can be applied to them and they also have a few special modifiers.

Visual representation

We recommend to get acquainted with the Adblock Plus filter cheatsheet, for better understanding of how exception rules should be made.

Modificador \ ProdutosAplicativos do CoreLibsAdGuard for ChromiumAdGuard for Chrome MV3AdGuard for FirefoxAdGuard para iOSAdGuard para SafariBloqueador de conteúdo do AdGuard
$content
$elemhide
$extension
$jsinject*[1]
$stealth
$urlblock*[2]*[2]
$genericblock*[3]*[3]
$generichide
$specifichide
nota
  • ✅ — fully supported
  • ✅ * — supported, but reliability may vary or limitations may occur; check the modifier description for more details
  • ❌ — not supported
info

By default, without specifying additional content type modifiers, exception rule modifiers override other basic rules only for main frame document requests (see $document for more information about main frame document).

Por exemplo:

  • The website example.com contains an iframe pointing to example1.com.
  • The rule #%#//console.log('test') is applied.

In this case, the log will appear twice in the console: once for the main frame document and once for iframe.

If you add the @@||example.com^$jsinject rule, the log will appear only once for iframe.

$content

Disables HTML filtering, $hls, $replace, and $jsonprune rules on the pages that match the rule.

Examples

  • @@||example.com^$content disables all content modifying rules on pages at example.com and all its subdomains.

$elemhide

Disables any cosmetic rules on the pages matching the rule.

Examples

  • @@||example.com^$elemhide disables all cosmetic rules on pages at example.com and all subdomains.
nota

You may use a shorter name (alias) instead of using the full modifier name: $ehide.

$extension

Disables specific userscripts or all userscripts for a given domain.

Syntax

$extension[="userscript_name1"[|"userscript_name2"[|"userscript_name3"[...]]]]

userscript_name(i) stands for a specific userscript name to be disabled by the modifier. The modifier can contain any number of userscript names or none. In the latter case the modifier disables all the userscripts.

Userscript names usually contain spaces or other special characters, which is why you should enclose the name in quotes. Both single (') and double (") ASCII quotes are supported. Multiple userscript names should be separated with a pipe (|). However, if a userscript name is a single word without any special characters, it can be used without quotes.

You can also exclude a userscript by adding a ~ character before it. In this case, the userscript will not be disabled by the modifier.

$extension=~"userscript name"
nota

When excluding a userscript, you must place ~ outside the quotes.

If a userscript's name includes quotes ("), commas (,), or pipes (|), they must be escaped with a backslash (\).

$extension="userscript name\, with \"quote\""

Examples

  • @@||example.com^$extension="AdGuard Assistant" disables the AdGuard Assistant userscript on example.com website.
  • @@||example.com^$extension=MyUserscript disables the MyUserscript userscript on example.com website.
  • @@||example.com^$extension='AdGuard Assistant'|'AdGuard Popup Blocker' disables both AdGuard Assistant and AdGuard Popup Blocker userscripts on example.com website.
  • @@||example.com^$extension=~"AdGuard Assistant" disables all user scripts on example.com website, except AdGuard Assistant.
  • @@||example.com^$extension=~"AdGuard Assistant"|~"AdGuard Popup Blocker" disables all user scripts on example.com website, except AdGuard Assistant and AdGuard Popup Blocker.
  • @@||example.com^$extension no userscript will work on webpages on example.com.
  • @@||example.com^$extension="AdGuard \"Assistant\"" disables the AdGuard "Assistant" userscript on example.com website.
Compatibility
  • Only AdGuard for Windows, Mac, Android are technically capable of using rules with $extension modifier.
  • Rules with $extension modifier with specific userscript name are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.13 or later.

$jsinject

Forbids adding of JavaScript code to the page. You can read about scriptlets and javascript rules further.

Examples

  • @@||example.com^$jsinject disables javascript on pages at example.com and all subdomains.
$jsinject modifier limitations
Limitations

Rules with the $jsinject modifier cannot be converted to DNR in AdGuard for Chrome MV3. We only use them in the TSUrlFilter engine to disable some cosmetic rules.

Compatibility

The $jsinject modifier is not supported by AdGuard for Chrome MV3 (yet) and AdGuard Content Blocker.

$stealth

Disables the Tracking protection (formerly Stealth Mode) module for all corresponding pages and requests.

Syntax

$stealth [= opt1 [| opt2 [| opt3 [...]]]]

opt(i) stand for certain Tracking protection options disabled by the modifier. The modifier can contain any number of specific options (see below) or none. In the latter case the modifier disables all the Tracking protection features.

The list of the available modifier options:

Examples

  • @@||example.com^$stealth disables Tracking protection for example.com (and subdomains) requests, except for blocking cookies and hiding tracking parameters (see below).
  • @@||domain.com^$script,stealth,domain=example.com disables Tracking protection only for script requests to domain.com (and its subdomains) on example.com and all its subdomains.
  • @@||example.com^$stealth=3p-cookie|dpi disables blocking third-party cookies and DPI fooling measures for example.com.
nota

Blocking cookies and removing tracking parameters is achieved by using rules with the $cookie, $urltransform and $removeparam modifiers. Exception rules that contain only the $stealth modifier will not do these things. Se você quiser desativar completamente todos os recursos de proteção contra rastreamento para um determinado domínio, deve incluir todos os três modificadores: @@||example.org^$stealth,removeparam,cookie.

Restrictions
  • Modifier options must be lowercase, i.e. $stealth=DPI will be rejected.
  • Modifier options cannot be negated, i.e. $stealth=~3p-cookie will be rejected.
  • AdGuard Browser Extension supports only searchqueries, donottrack, referrer, xclientdata, 1p-cookie and 3p-cookie options.
Compatibility
  • Tracking protection (formerly Stealth Mode) is available in AdGuard for Windows, AdGuard for Mac, AdGuard for Android, and AdGuard Browser Extension for Firefox and Chromium-based browsers, except AdGuard for Chrome MV3. All other products will ignore the rules with $stealth modifier.
  • Rules with $stealth modifier with specific options are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.10 or later, and AdGuard Browser Extension with TSUrlFilter v3.0.0 or later.

$urlblock

Disables blocking of all requests sent from the pages matching the rule and disables all $cookie rules.

Examples

  • @@||example.com^$urlblock — any requests sent from the pages at example.com and all subdomains are not going to be blocked.
$urlblock modifier limitations
Limitations

In AdGuard for iOS and AdGuard for Safari, rules with $urlblock work as $document exclusion — unblock everything.

Compatibility

Rules with $urlblock modifier are not supported by AdGuard Content Blocker, and AdGuard for Chrome MV3.

Generic rules

Before we can proceed to the next modifiers, we have to make a definition of generic rules. The rule is generic if it is not limited to specific domains. Wildcard character * is supported as well.

For example, these rules are generic:

###banner
*###banner
#@#.adsblock
*#@#.adsblock
~domain.com###banner
||domain.com^
||domain.com^$domain=~example.com

And these are not:

domain.com###banner
||domain.com^$domain=example.com

$genericblock

Disables generic basic rules on pages that correspond to exception rule.

Examples

  • @@||example.com^$genericblock disables generic basic rules on any pages at example.com and all subdomains.
$genericblock modifier limitations
Limitations

In AdGuard for iOS and AdGuard for Safari, rules with $genericblock work as $document exclusion — unblock everything.

Compatibility

Rules with $genericblock modifier are not supported by AdGuard Content Blocker, and AdGuard for Chrome MV3.

$generichide

Disables all generic cosmetic rules on pages that correspond to the exception rule.

Examples

  • @@||example.com^$generichide disables generic cosmetic rules on any pages at example.com and its subdomains.
nota

You may use a shorter name (alias) instead of using the full modifier name: $ghide.

specifichide

Disables all specific element hiding and CSS rules, but not general ones. Has an opposite effect to $generichide.

Examples

  • @@||example.org^$specifichide desativar example.org##.banner, mas não ##.banner.
nota

You may use a shorter name (alias) instead of using the full modifier name: $shide.

nota

All cosmetic rules — not just specific ones — can be disabled by $elemhide modifier.

Compatibility

Rules with $specifichide modifier are not supported by AdGuard for iOS, AdGuard for Safari, and AdGuard Content Blocker.

Advanced capabilities

These modifiers are able to completely change the behavior of basic rules.

Modificador \ ProdutosAplicativos do CoreLibsAdGuard for ChromiumAdGuard for Chrome MV3AdGuard for FirefoxAdGuard para iOSAdGuard para SafariBloqueador de conteúdo do AdGuard
$all*[1]
$badfilter*[2]
$cookie*[3]
$csp
$hls
$inline-font
$inline-script
$jsonprune
$xmlprune
$network
$permissions*[4]*[4]
$redirect*[5]
$redirect-rule
$referrerpolicy
$removeheader
$removeparam*[6]
$replace
$urltransform
noop
$empty 👎
$mp4 👎
nota
  • ✅ — fully supported
  • ✅ * — supported, but reliability may vary or limitations may occur; check the modifier description for more details
  • ⏳ — recurso que está planejado para ser implementado, mas ainda não está disponível em nenhum produto
  • ❌ — not supported
  • 👎 — deprecated; still supported but will be removed in the future

$all

$all modifier is made of all content-types modifiers and $popup. E.g. a regra ||example.org^$all está sendo convertida na regra:

||example.org^$document,subdocument,font,image,media,object,other,ping,script,stylesheet,websocket,xmlhttprequest,popup
Restrictions

This modifier cannot be used as an exception with the @@ mark.

$all modifier limitations
Limitations

Since $popup is a part if $all, the $all modifier is not supported by AdGuard for Chrome MV3 because of $popup modifier limitations.

Compatibility

Rules with $all modifier are not supported by AdGuard Content Blocker.

$badfilter

The rules with the $badfilter modifier disable other basic rules to which they refer. It means that the text of the disabled rule should match the text of the $badfilter rule (without the $badfilter modifier).

Examples

  • ||example.com$badfilter disables ||example.com
  • ||example.com$image,badfilter disables ||example.com$image
  • @@||example.com$badfilter disables @@||example.com
  • ||example.com$domain=domain.com,badfilter disables ||example.com$domain=domain.com

Rules with $badfilter modifier can disable other basic rules for specific domains if they fulfill the following conditions:

  1. The rule has a $domain modifier
  2. The rule does not have a negated domain ~ in $domain modifier 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 works here as well.

Examples

  • /some$domain=example.com|example.org|example.io is disabled for example.com by /some$domain=example.com,badfilter
  • /some$domain=example.com|example.org|example.io is disabled for example.com and example.org by /some$domain=example.com|example.org,badfilter
  • /some$domain=example.com|example.org and /some$domain=example.io are disabled completely by /some$domain=example.com|example.org|example.io,badfilter
  • /some$domain=example.com|example.org|example.io is disabled completely by /some$domain=example.*,badfilter
  • /some$domain=example.* is disabled for example.com and example.org by /some$domain=example.com|example.org,badfilter
  • /some$domain=example.com|example.org|example.io is NOT disabled for example.com by /some$domain=example.com|~example.org,badfilter because the value of $domain modifier contains a negated domain
$badfilter modifier limitations
Limitations

In AdGuard for Chrome MV3 a rule with the $badfilter modifier is applied in DNR only if it fully cancels the source rule. We cannot calculate it if it is only partially canceled. Examples.

Compatibility

Rules with $badfilter modifier are not supported by AdGuard Content Blocker.

The $cookie modifier completely changes rule behavior. Instead of blocking a request, this modifier makes AdGuard suppress or modify the Cookie and Set-Cookie headers.

Multiple rules matching a single request

In case if multiple $cookie rules match a single request, we will apply each of them one by one.

Syntax

$cookie [= name[; maxAge = seconds [; sameSite = strategy ]]]

where:

  • name — optional, string or regular expression to match cookie name.
  • seconds — number of seconds for current time to offset the expiration date of cookie.
  • strategy — string for Same-Site strategy to be applied to the cookie.

For example,

||example.org^$cookie=NAME;maxAge=3600;sameSite=lax

every time AdGuard encounters a cookie called NAME in a request to example.org, it will do the following:

  • Set its expiration date to current time plus 3600 seconds
  • Makes the cookie use Same-Site "lax" strategy.

Escaping special characters

If regular expression name is used for matching, two characters must be escaped: comma , and dollar sign $. Use backslash \ to escape each of them. For example, escaped comma looks like this: \,.

Examples

  • ||example.org^$cookie blocks all cookies set by example.org; this is an equivalent to setting maxAge=0
  • $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

There are two methods to deactivate $cookie rules: the primary method involves using an exception marked with @@@@||example.org^$cookie. The alternative method employs a $urlblock exception (also included under the $document exception alias — $elemhide,jsinject,content,urlblock,extension). Here's how it works:

  • @@||example.org^$cookie unblocks all cookies set by example.org
  • @@||example.org^$urlblock unblocks all cookies set by example.org and disables blocking of all requests sent from example.org
  • @@||example.org^$cookie=concept unblocks a single cookie named concept
  • @@||example.org^$cookie=/^_ga_/ unblocks every cookie that matches the regular expression
Limitations

In AdGuard for Chrome MV3 we delete cookies in 2 ways: from content-script side (to which we have access) and from onBeforeSendHeaders listener. Since onBeforeSendHeaders and other listeners are no longer blocking, we are not able to delete them in all cases. You can check if a rule works with this test.

Restrictions

$cookie rules support these types of modifiers: $domain, $~domain, $important, $third-party, $~third-party, strict-third-party, and strict-first-party.

Compatibility

Rules with $cookie modifier are not supported by AdGuard Content Blocker, AdGuard for iOS, and AdGuard for Safari.

$csp

This modifier completely changes the rule behavior. If it is applied to a rule, the rule will not block the matching request. Response headers will be modified instead.

info

In order to use this type of rules, it is required to have the basic understanding of the Content Security Policy security layer.

For the requests matching a $csp rule, we will strengthen response security policy by enhancing the content security policy, similar to the content security policy of the $csp modifier contents. $csp rules are applied independently from any other rule type. Only document-level exceptions can influence it (see the examples section), but no other basic rules.

Multiple rules matching a single request

In case if multiple $csp rules match a single request, we will apply each of them.

Syntax

$csp value syntax is similar to the Content Security Policy header syntax.

$csp value can be empty in the case of exception rules. See examples section below.

Examples

  • ||example.org^$csp=frame-src 'none' blocks all frames on example.org and its subdomains.
  • @@||example.org/page/*$csp=frame-src 'none' disables all rules with the $csp modifier exactly matching frame-src 'none' on all the pages matching the rule pattern. For instance, the rule above.
  • @@||example.org/page/*$csp disables all the $csp rules on all the pages matching the rule pattern.
  • ||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.
Restrictions
  • There are a few characters forbidden in the $csp value: ,, $.
  • $csp rules support three types of modifiers: $domain, $important, $subdocument.
  • Rules with report-* directives are considered invalid.
Compatibility

Rules with $csp modifier are not supported by AdGuard Content Blocker, AdGuard for iOS and AdGuard for Safari.

$hls

$hls rules modify the response of a matching request. They are intended as a convenient way to remove segments from HLS playlists (RFC 8216).

nota

The word "segment" in this document means either a "Media Segment" or a "playlist" as part of a "Master Playlist": $hls rules do not distinguish between a "Master Playlist" and a "Media Playlist".

Syntax

  • ||example.org^$hls=urlpattern removes segments whose URL matches the URL pattern urlpattern. The pattern works just like the one in basic URL rules, however, the characters /, $ and , must be escaped with \ inside urlpattern.
  • ||example.org^$hls=/regexp/options removes segments where the URL or one of the tags (for certain options, if present) is matched by the regular expression regexp. Available options are:
    • t — instead of testing the segment's URL, test each of the segment's tags against the regular expression. A segment with a matching tag is removed;
    • i — make the regular expression case-insensitive.

The characters /, $ and , must be escaped with \ inside regexp.

Exceptions

Basic URL exceptions shall not disable rules with the $hls modifier. They can be disabled as described below:

  • @@||example.org^$hls disables all $hls rules for responses from URLs matching ||example.org^.
  • @@||example.org^$hls=text disables all $hls rules with the value of the $hls modifier equal to text for responses from URLs matching ||example.org^.
dica

$hls rules can also be disabled by $document, $content and $urlblock exception rules.

nota

When multiple $hls rules match the same request, their effect is cumulative.

Examples

  • ||example.org^$hls=\/videoplayback^?*&source=dclk_video_ads removes all segments with the matching URL.
  • ||example.org^$hls=/\/videoplayback\/?\?.*\&source=dclk_video_ads/i achieves more or less the same with a regular expression instead of a URL pattern.
  • ||example.org^$hls=/#UPLYNK-SEGMENT:.*\,ad/t removes all segments which have the matching tag.

Anatomy of an HLS playlist

A quick summary of the specification:

  1. An HLS playlist is a collection of text lines
  2. A line may be empty, a comment (starts with #), a tag (also starts with #, can only be recognized by name) or a URL
  3. A URL line is called a "segment"
  4. Tags may apply to a single segment, i.e. the first URL line after the tag, to all segments following the tag and until the tag with the same name, or to the whole playlist

Some points specific to the operation of $hls rules:

  1. When a segment is removed, all of the tags that apply only to that segment are also removed
  2. When there is a tag that applies to multiple segments, and all of those segments are removed, the tag is also removed
  3. Since there is no way to recognize different kinds of tags by syntax, we recognize all of the tags specified by the RFC, plus some non-standard tags that we have seen in the field. Any lines starting with # and not recognized as a tag are passed through without modification, and are not matched against the rules
  4. Tags will not be matched if they apply to the entire playlist, and $hls rules cannot be used to remove them, as these rule types are intended for segment removals. If you know what you are doing, you can use $replace rules to remove or rewrite just a single tag from the playlist

An example of a transformation done by the rules:

Original response
#EXTM3U
#EXT-X-TARGETDURATION:10
#EXTINF,5
preroll.ts
#UPLYNK-SEGMENT:abc123,ad
#UPLYNK-KEY:aabb1122
#EXT-X-DISCONTINUITY
#EXTINF,10
01.ts
#EXTINF,10
02.ts
#UPLYNK-SEGMENT:abc123,segment
#UPLYNK-KEY:ccdd2233
#EXT-X-DISCONTINUITY
#EXTINF,10
01.ts
#EXTINF,10
02.ts
#EXT-X-ENDLIST
Applied rules
||example.org^$hls=preroll
||example.org^$hls=/#UPLYNK-SEGMENT:.*\,ad/t
Modified response
#EXTM3U
#EXT-X-TARGETDURATION:10
#UPLYNK-SEGMENT:abc123,segment
#UPLYNK-KEY:ccdd2233
#EXT-X-DISCONTINUITY
#EXTINF,10
01.ts
#EXTINF,10
02.ts
#EXT-X-ENDLIST
Restrictions
  • Rules with the $hls modifier can only be used in trusted filters.
  • $hls rules are compatible with the modifiers $domain, $third-party, $strict-third-party, $strict-first-party, $app, $important, $match-case, and $xmlhttprequest only.
  • $hls rules only apply to HLS playlists, which are UTF-8 encoded text starting with the line #EXTM3U. Any other response will not be modified by these rules.
  • $hls rules do not apply if the size of the original response is more than 10 MB.
Compatibility

Rules with the $hls modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.10 or later.

$inline-script

The $inline-script modifier is designed to block inline JavaScript embedded into the web page, using Content Security Policy (CSP). It improves security and privacy by preventing application of inline ads or potentially malicious scripts. The rule ||example.org^$inline-script is converting into the CSP-syntax rule:

||example.org^$csp=script-src 'self' 'unsafe-eval' http: https: data: blob: mediastream: filesystem:

$inline-font

The $inline-font modifier is designed to block inline fonts embedded into the web page, using Content Security Policy (CSP). It improves security and privacy by preventing application of inline fonts that could be used for data collection and fingerprinting. The rule ||example.org^$inline-font is converting into the CSP-syntax rule:

||example.org^$csp=font-src 'self' 'unsafe-eval' http: https: data: blob: mediastream: filesystem:

$jsonprune

$jsonprune rules modify the response to a matching request by removing JSON items that match a modified JSONPath expression. They do not modify responses which are not valid JSON documents.

In AdGuard for Windows, Mac, and Android with CoreLibs v1.11 or later, $jsonprune also supports modifying JSONP (padded JSON) documents.

Syntax

  • ||example.org^$jsonprune=expression removes items that match the modified JSONPath expression expression from the response.

Due to the way rule parsing works, the characters $ and , must be escaped with \ inside expression.

The modified JSONPath syntax has the following differences from the original:

  1. Script expressions are not supported
  2. The supported filter expressions are:
    • ?(has <key>) — true if the current object has the specified key
    • ?(key-eq <key> <value>) — true if the current object has the specified key, and its value is equal to the specified value
    • ?(key-substr <key> <value>) — true if the specified value is a substring of the value of the specified key of the current object
  3. Whitespace outside of double- or single-quoted strings has no meaning
  4. Both double- and single-quoted strings can be used
  5. Expressions ending with .. are not supported
  6. Multiple array slices can be specified in square brackets

There are various online tools that make working with JSONPath expressions more convenient:

https://www.site24x7.com/tools/jsonpath-finder-validator.html https://jsonpathfinder.com/ https://jsonpath.com/

Keep in mind, though, that all JSONPath implementations have unique features/quirks and are subtly incompatible with each other.

Exceptions

Basic URL exceptions shall not disable rules with the $jsonprune modifier. They can be disabled as described below:

  • @@||example.org^$jsonprune disables all $jsonprune rules for responses from URLs matching ||example.org^.
  • @@||example.org^$jsonprune=text disables all $jsonprune rules with the value of the $jsonprune modifier equal to text for responses from URLs matching ||example.org^.

$jsonprune rules can also be disabled by $document, $content and $urlblock exception rules.

nota

When multiple $jsonprune rules match the same request, they are sorted in lexicographical order, the first rule is applied to the original response, and each of the remaining rules is applied to the result of applying the previous one.

Examples

  • ||example.org^$jsonprune=\$..[one\, "two three"] removes all occurrences of the keys "one" and "two three" anywhere in the JSON document.
Input
{
"one": 1,
"two": {
"two three": 23,
"four five": 45
}
}
Output
{
"two": {
"four five": 45
}
}
  • ||example.org^$jsonprune=\$.a[?(has ad_origin)] removes all children of a that have an ad_origin key.
Input
{
"a": [
{
"ad_origin": "https://example.org",
"b": 42
},
{
"b": 1234
}
]
}
Output
{
"a": [
{
"b": 1234
}
]
}
  • ||example.org^$jsonprune=\$.*.*[?(key-eq 'Some key' 'Some value')] removes all items that are at nesting level 3 and have a property "Some key" equal to "Some value".
Input
{
"a": {"b": {"c": {"Some key": "Some value"}, "d": {"Some key": "Other value"}}},
"e": {"f": [{"Some key": "Some value"}, {"Some key": "Other value"}]}
}
Output
{
"a": {"b": {"d": {"Some key": "Other value"}}},
"e": {"f": [{"Some key": "Other value"}]}
}

Nested JSONPath expressions

In AdGuard for Windows, Mac and Android with CoreLibs v1.11 or later, JSONPath expressions may be used as keys in filter expressions.

  • ||example.org^$jsonprune=\$.elems[?(has "\$.a.b.c")] removes all children of elems which have a property selectable by the JSONPath expression $.a.b.c.
Input
{
"elems": [
{
"a": {"b": {"c": 123}},
"k": "v"
},
{
"d": {"e": {"f": 123}},
"k1": "v1"
}
]
}
Output
{
"elems": [
{
"d": {"e": {"f": 123}},
"k1": "v1"
}
]
}
  • ||example.org^$jsonprune=\$.elems[?(key-eq "\$.a.b.c" "abc")] removes all children of elems which have a property selectable by the JSONPath expression $.a.b.c with a value equal to "abc".
Input
{
"elems": [
{
"a": {"b": {"c": 123}},
},
{
"a": {"b": {"c": "abc"}}
}
]
}
Output
{
"elems": [
{
"a": {"b": {"c": 123}}
}
]
}
Restrictions
  • $jsonprune rules are only compatible with these modifiers: $domain, $third-party, $strict-third-party, $strict-first-party, $app, $important, $match-case, and $xmlhttprequest.
  • $jsonprune rules do not apply if the size of the original response is greater than 10 MB.
Compatibility

Rules with the $jsonprune modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.10 or later.

$xmlprune

$xmlprune rules modify the response to a matching request by removing XML items that match an XPath 1.0 expression. The expression must return a node-set. $xmlprune rules do not modify responses which are not well-formed XML documents.

Syntax

  • ||example.org^$xmlprune=expression removes items that match the XPath expression expression from the response.

Due to the way rule parsing works, the characters $ and , must be escaped with \ inside expression.

Exceptions

Basic URL exceptions shall not disable rules with the $xmlprune modifier. They can be disabled as described below:

  • @@||example.org^$xmlprune disables all $xmlprune rules for responses from URLs matching ||example.org^.
  • @@||example.org^$xmlprune=text disables all $xmlprune rules with the value of the $xmlprune modifier equal to text for responses from URLs matching ||example.org^.

$xmlprune rules can also be disabled by $document, $content and $urlblock exception rules.

nota

When multiple $xmlprune rules match the same request, they are applied in lexicographical order.

Examples

  • ||example.org^$xmlprune=/bookstore/book[position() mod 2 = 1] removes odd-numbered books from the bookstore.
Input
<?xml version="1.0" encoding="UTF-8"?>

<bookstore>

<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>

<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>

<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>

</bookstore>
Output
<?xml version="1.0" encoding="UTF-8"?>

<bookstore>



<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>



<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>

</bookstore>
  • ||example.org^$xmlprune=/bookstore/book[year = 2003] removes books from the year 2003 from the bookstore.
Input
<?xml version="1.0" encoding="UTF-8"?>

<bookstore>

<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>

<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>

<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>

</bookstore>
Output
<?xml version="1.0" encoding="UTF-8"?>

<bookstore>

<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>





</bookstore>
  • ||example.org^$xmlprune=//*/@* removes all attributes from all elements.
Input
<?xml version="1.0" encoding="UTF-8"?>

<bookstore location="cy">

<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

</bookstore>
Output
<?xml version="1.0" encoding="UTF-8"?>

<bookstore>

<book>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

</bookstore>
Restrictions
  • $xmlprune rules are only compatible with these modifiers: $domain, $third-party, $strict-third-party, $strict-first-party, $app, $important, $match-case, and $xmlhttprequest.
  • $xmlprune rules do not apply if the size of the original response is greater than 10 MB.
Compatibility

Rules with the $xmlprune modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.15 or later.

$network

This is basically a Firewall-like rule allowing to fully block or unblock access to a specified remote address.

  1. $network rules match IP addresses only! You cannot use them to block or unblock access to a domain.
  2. To match an IPv6 address, you have to use the collapsed syntax, e.g. use [2001:4860:4860::8888]$network instead of [2001:4860:4860:0:0:0:0:8888]$network.
  3. An allowlist $network rule makes AdGuard bypass data to the matching endpoint, hence there will be no further filtering at all.
  4. If the IP part starts and ends with / character, it is treated as a regular expression.

We recommend to get acquainted with this article for better understanding of regular expressions.

Restrictions

The $network modifier can only be used in rules together with the $app and $important modifiers, and not with any other modifiers.

Examples

  • 174.129.166.49:3478^$network blocks access to 174.129.166.49:3478 (but not to 174.129.166.49:34788).
  • [2001:4860:4860::8888]:443^$network blocks access to [2001:4860:4860::8888]:443.
  • 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.
  • /.+:3[0-9]{4}/$network blocks access to any port from 30000 to 39999.
  • /8.8.8.(:?8|4)/$network blocks access to both 8.8.8.8 and 8.8.8.4.
Compatibility

Only AdGuard for Windows, Mac, and Android are technically capable of using rules with $network modifier.

$permissions

This modifier completely changes the rule behavior. If it is applied to a rule, the rule will not block the matching request. Response headers will be modified instead.

info

In order to use this type of rules, it is required to have a basic understanding of the Permissions Policy security layer.

For the requests matching a $permissions rule, AdGuard strengthens response's permissions policy by adding an additional permission policy equal to the $permissions modifier contents. $permissions rules are applied independently from any other rule type. Only document-level exceptions can influence it (see the examples section), but no other basic rules.

Syntax

$permissions value syntax is identical to that of the Permissions-Policy header syntax with the following exceptions:

  1. A comma that separates multiple features MUST be escaped — see examples below.
  2. A pipe character (|) can be used instead of a comma to separate features.

The list of available directives is available here.

$permissions value can be empty in the case of exception rules — see examples below.

Examples

  • ||example.org^$permissions=autoplay=() disallows autoplay media requested through the HTMLMediaElement interface across example.org.
  • @@||example.org/page/*$permissions=autoplay=() disables all rules with the $permissions modifier exactly matching autoplay=() on all the pages matching the rule pattern. For instance, the rule above. It is important to note that the exception rule only takes effect in the case of an exact value match. For example, if you want to disable the rule $permissions=a=()\,b=(), you need exception rule @@$permissions=a=()\,b=(), and not @@$permissions=b=()\,a=(), nor @@$permissions=b=() because b=()\,a=() or b=() does not match with a=()\,b=().
  • @@||example.org/page/*$permissions disables all the $permissions rules on all the pages matching the rule pattern.
  • $domain=example.org|example.com,permissions=storage-access=()\, camera=() disallows using the Storage Access API to request access to unpartitioned cookies and using video input devices across example.org and example.com.
  • $domain=example.org|example.com,permissions=storage-access=()|camera=() does the same — a | can be used to separate the features instead of an escaped comma.
  • @@||example.org^$document or @@||example.org^$urlblock disables all the $permission rules on all the pages matching the rule pattern.
nota

$permissions rules only take effect for main frame and sub frame requests. This means they are applied when a page is loaded or when an iframe is loaded.

nota

If there are multiple $permissions rules that match the same request, multiple Permissions-Policy headers will be added to the response for each rule with their $permissions value. So if you have two rules: ||example.org^$permissions=autoplay=() and ||example.org^$permissions=geolocation=()\,camera=() that match the same request, the response will contain two Permissions-Policy headers: autoplay=() and geolocation=()\,camera=().

$permissions modifier limitations
Limitations

Firefox ignores the Permissions-Policy header. For more information, see this issue.

Restrictions
  1. Characters forbidden in the $permissions value: $.
  2. $permissions is compatible with a limited set of modifiers: $domain, $important, $subdocument, and content-type modifiers.
  3. $permissions rules that do not have any content-type modifiers will match only requests where content type is document.
Compatibility
  • Rules with the $permissions modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.11 or later, and AdGuard Browser Extension with TSUrlFilter v3.0.0 or later.
  • Pipe separator | instead of escaped comma is supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.14 or later, and AdGuard Browser Extension with TSUrlFilter v3.0.0 or later.

$redirect

AdGuard is able to redirect web requests to a local "resource".

Syntax

AdGuard uses the same filtering rule syntax as uBlock Origin. Also, it is compatible with ABP $rewrite=abp-resource modifier.

$redirect is a modifier for the basic filtering 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.

Disabling $redirect rules
  • ||example.org/script.js$script,redirect=noopjs — this rule redirects all requests to example.org/script.js to the resource named noopjs.
  • ||example.org/test.mp4$media,redirect=noopmp4-1s — this rule redirects all requests to example.org/test.mp4 to the resource named noopmp4-1s.
  • @@||example.org^$redirect will disable all $redirect rules for URLs that match ||example.org^.
  • @@||example.org^$redirect=nooptext will disable all rules with $redirect=nooptext for any request that matches ||example.org^.

More information on redirects and their usage is available on GitHub.

Priorities of $redirect rules

$redirect rules have higher priority than regular basic blocking rules. This means that if there is a basic blocking rule, the $redirect rule will override it. Allowlist rules with @@ mark have higher priority than $redirect rules. If a basic rule with the $important modifier and the $redirect rule matches the same URL, the latter is overridden unless it's also marked as $important.

In short: $important > @@ > $redirect > basic rules.

Go to rules priorities for more details.

$redirect modifier limitations
Limitations

In AdGuard for Chrome MV3 allowlist rules with $redirect are not supported.

Compatibility

$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.

Go to rules priorities for more details.

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.

Examples

||example.org/script.js
||example.org^$redirect-rule=noopjs

In this case, only requests to example.org/script.js will be "redirected" to noopjs. All other requests to example.org will be kept intact.

$referrerpolicy

These rules allow overriding of a page's referrer policy. Responses to matching requests will have all of their Referrer-Policy headers replaced with a single header with the value equal to the matching rule's modifier value. If the response carries an HTML document with a <meta name="referrer"... tag, the content attribute of the tag will also be replaced with the modifier value.

An exception rule with a modifier value disables the blocking rule with the same modifier value. An exception rule without a modifier value disables all matched referrer-policy rules.

If a request matches multiple $referrerpolicy rules not disabled by exceptions, only one of them (it is not specified which one) is applied. $referrerpolicy rules without specified content-type modifiers apply to $document and $subdocument content types.

Examples

  • ||example.com^$referrerpolicy=unsafe-url overrides the referrer policy for example.com with unsafe-url.
  • @@||example.com^$referrerpolicy=unsafe-url disables the previous rule.
  • @@||example.com/abcd.html^$referrerpolicy disables all $referrerpolicy rules on example.com/abcd.html.
Compatibility

Rules with the $referrerpolicy modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.12 or later.

$removeheader

Rules with $removeheader modifier are intended to remove headers from HTTP requests and responses. The initial motivation for this rule type is to be able to get rid of the Refresh header which is often used to redirect users to an undesirable location. However, this is not the only case where this modifier can be useful.

Just like $csp, $redirect, $removeparam, and $cookie, this modifier exists independently, rules with it do not depend on the regular basic rules, i.e. regular exception or blocking rules will not affect it. By default, it only affects response headers. However, you can also change it to remove headers from HTTP requests as well.

Syntax

Basic syntax

  • ||example.org^$removeheader=header-name removes a response header called header-name
  • ||example.org^$removeheader=request:header-name removes a request header called header-name

$removeheader is case-insensitive, but we suggest always using lower case.

Negating $removeheader

This type of rules works pretty much the same way it works with $csp and $redirect modifiers.

Use @@ to negate $removeheader:

  • @@||example.org^$removeheader negates all $removeheader rules for URLs that match ||example.org^.
  • @@||example.org^$removeheader=header negates the rule with $removeheader=header for any request matching ||example.org^.

$removeheader rules can also be disabled by $document and $urlblock exception rules. But basic exception rules without modifiers will not do that. For example, @@||example.com^ will not disable $removeheader=p for requests to example.com, but @@||example.com^$urlblock will.

nota

In case of multiple $removeheader rules matching a single request, we will apply each of them one by one.

Examples

  • ||example.org^$removeheader=refresh removes Refresh header from all HTTP responses returned by example.org and its subdomains.

  • ||example.org^$removeheader=request:x-client-data removes X-Client-Data header from all HTTP requests.

  • Next block of rules removes Refresh and Location headers from all HTTP responses returned by example.org save for requests to example.org/path/*, for which no headers will be removed:

    ||example.org^$removeheader=refresh
    ||example.org^$removeheader=location
    @@||example.org/path/$removeheader
Restrictions

This type of rules can only be used in trusted filters.

  1. In order to avoid compromising the security $removeheader cannot remove headers from the list below:

    • access-control-allow-origin
    • access-control-allow-credentials
    • access-control-allow-headers
    • access-control-allow-methods
    • access-control-expose-headers
    • access-control-max-age
    • access-control-request-headers
    • access-control-request-method
    • origin
    • timing-allow-origin
    • allow
    • cross-origin-embedder-policy
    • cross-origin-opener-policy
    • cross-origin-resource-policy
    • content-security-policy
    • content-security-policy-report-only
    • expect-ct
    • feature-policy
    • origin-isolation
    • strict-transport-security
    • upgrade-insecure-requests
    • x-content-type-options
    • x-download-options
    • x-frame-options
    • x-permitted-cross-domain-policies
    • x-powered-by
    • x-xss-protection
    • public-key-pins
    • public-key-pins-report-only
    • sec-websocket-key
    • sec-websocket-extensions
    • sec-websocket-accept
    • sec-websocket-protocol
    • sec-websocket-version
    • p3p
    • sec-fetch-mode
    • sec-fetch-dest
    • sec-fetch-site
    • sec-fetch-user
    • referrer-policy
    • content-type
    • content-length
    • accept
    • accept-encoding
    • host
    • connection
    • transfer-encoding
    • upgrade
  2. $removeheader rules are only compatible with $domain, $third-party, $strict-third-party, $strict-first-party, $app, $important, $match-case, and content-type modifiers such as $script and $stylesheet. The rules which have any other modifiers are considered invalid and will be discarded.

Compatibility

Rules with $removeheader modifier are supported by AdGuard for Windows, AdGuard for Mac, AdGuard for Android, and AdGuard Browser Extension for Chrome, Firefox, and Edge.

$removeparam

nota

$queryprune is an alias of $removeparam. Since $queryprune is deprecated, avoid using it and use $removeparam instead.

Rules with $removeparam modifier are intended to strip query parameters from requests' URLs. Please note that such rules are only applied to GET, HEAD, OPTIONS, and sometimes POST requests.

Syntax

Basic syntax

  • $removeparam=param removes query parameter with the name param from URLs of any request, e.g. a request to http://example.com/page?param=1&another=2 will be transformed into http://example.com/page?another=2.

Regular expressions

You can also use regular expressions to match query parameters and/or their values:

  • $removeparam=/regexp/[options] — removes query parameters that matches the regexp regular expression from URLs of any request. Unlike basic syntax, it means "remove query parameters normalized to a name=value string which match the regexp regular expression". [options] here is the list of regular expression options. At the moment, the only supported option is i which makes matching case-insensitive.

Escaping special characters

Special characters should be URL-encoded in a rule to correctly match the URL text.

For example, to remove ?$param=true, you should use the $removeparam=%24param rule.

nota

Spaces and commas should also be URL-encoded, otherwise the rule won't match the URL. However, ., -, _, and ~ should be used as they are, since they are not marked as reserved characters in URL encoding.

Remember to escape special characters like . in the regular expressions. Use the \ character to do this. For example, an escaped dot should look like this: \..

nota

Regexp-type rules apply to both the name and value of the parameter. To minimize errors, it is safer to start each regexp with /^, unless you are specifically targeting parameter values.

Remove all query parameters

Specify naked $removeparam to remove all query parameters:

  • ||example.org^$removeparam — removes all query parameters from URLs matching ||example.org^.

Inversion

Use ~ to apply inversion:

  • $removeparam=~param — removes all query parameters with the name different from param.
  • $removeparam=~/regexp/ — removes all query parameters that do not match the regexp regular expression.
nota

If ~ does not appear at the beginning of the rule, it is treated as a symbol in the text.

Negating $removeparam

This sort of rules work pretty much the same way it works with $csp and $redirect modifiers.

Use @@ to negate $removeparam:

  • @@||example.org^$removeparam negates all $removeparam rules for URLs that match ||example.org^.
  • @@||example.org^$removeparam=param negates the rule with $removeparam=param for any request matching ||example.org^.
  • @@||example.org^$removeparam=/regexp/ negates the rule with $removeparam=/regexp/ for any request matching ||example.org^.

Multiple rules matching a single request

In the case when multiple $removeparam rules match a single request, each of them will be applied one by one.

Examples

$removeparam=/^(utm_source|utm_medium|utm_term)=/
$removeparam=/^(utm_content|utm_campaign|utm_referrer)=/
@@||example.com^$removeparam

With these rules some UTM parameters will be stripped out from any request, except that requests to example.com will not be stripped at all, e.g. http://google.com/page?utm_source=s&utm_referrer=fb.com&utm_content=img will be transformed to http://google.com/page, but http://example.com/page?utm_source=s&utm_referrer=fb.com&utm_content=img will not be affected by the blocking rule.

  • $removeparam=utm_source removes utm_source query parameter from all requests.

  • $removeparam=/utm_.*/ removes all utm_* query parameters from URL queries of any request, e.g. a request to http://example.com/page?utm_source=test will be transformed to http://example.com/page.

  • $removeparam=/^utm_source=campaign$/ removes utm_source query parameter with the value equal to campaign. It does not touch other utm_source parameters.

Negating one $removeparam rule and replacing it with a different rule

$removeparam=/^(gclid|yclid|fbclid)=/
@@||example.com^$removeparam=/^(gclid|yclid|fbclid)=/
||example.com^$removeparam=/^(yclid|fbclid)=/

With these rules, Google, Yandex, and Facebook Click IDs will be removed from all requests. There is one exception: Google Click ID (gclid) will not be removed from requests to example.com.

Negating $removeparam for all parameters

$removeparam=/^(utm_source|utm_medium|utm_term)=/
$removeparam=/^(utm_content|utm_campaign|utm_referrer)=/
@@||example.com^$removeparam

With these rules, specified UTM parameters will be removed from any request save for requests to example.org.

$removeparam rules can also be disabled by $document and $urlblock exception rules. But basic exception rules without modifiers do not do that. For example, @@||example.com^ will not disable $removeparam=p for requests to example.com, but @@||example.com^$urlblock will.

$removeparam modifier limitations
Limitations

AdGuard for Chrome MV3 has some limitations:

  • Regular expressions, negation and allowlist rules are not supported.

  • Group of similar $removeparam rules will be combined into one. Example:

    ||testcases.adguard.com$xmlhttprequest,removeparam=p1case1
    ||testcases.adguard.com$xmlhttprequest,removeparam=p2case1
    ||testcases.adguard.com$xmlhttprequest,removeparam=P3Case1
    $xmlhttprequest,removeparam=p1case2

    é convertido para

    [
    {
    "id": 1,
    "action": {
    "type": "redirect",
    "redirect": {
    "transform": {
    "queryTransform": {
    "removeParams": [
    "p1case1",
    "p2case1",
    "P3Case1"
    ]
    }
    }
    }
    },
    "condition": {
    "urlFilter": "||testcases.adguard.com",
    "resourceTypes": [
    "xmlhttprequest"
    ],
    "isUrlFilterCaseSensitive": false
    }
    },
    {
    "id": 4,
    "action": {
    "type": "redirect",
    "redirect": {
    "transform": {
    "queryTransform": {
    "removeParams": [
    "p1case2"
    ]
    }
    }
    }
    },
    "condition": {
    "resourceTypes": [
    "xmlhttprequest"
    ],
    "isUrlFilterCaseSensitive": false
    }
    }
    ]
Restrictions
  1. Rules with the $removeparam modifier can only be used in trusted filters.
  2. $removeparam rules are compatible with basic modifiers, content-type modifiers, and with the $important and $app modifiers. Rules with any other modifiers are considered invalid and will be discarded.
  3. $removeparam rules without content type modifiers will only match requests where the content type is document.
Compatibility
  • Rules with $removeparam modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.7 or later, and AdGuard Browser Extension v3.6 or later.
  • $removeparam syntax for regular expressions is supported AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.8 or later, and AdGuard Browser Extension v4.0 or later.
  • POST request types are supported only by AdGuard for Windows, Mac, and Android with CoreLibs v1.10 or later, and AdGuard Browser Extension with TSWebExtension v0.4.6 or later.

$replace

This modifier completely changes the rule behavior. If it is applied, the rule will not block the request. The response is going to be modified instead.

You will need some knowledge of regular expressions to use $replace modifier.

Features

  • $replace rules apply to any text response, but will not apply to binary (media, image, object, etc.).
  • $replace rules do not apply if the size of the original response is more than 10 MB.
  • $replace rules have a higher priority than other basic rules (including exception rules). So if a request natches two different rules, one of which has the $replace modifier, this rule will be applied.
  • Document-level exception rules with $content or $document modifiers do disable $replace rules for requests matching them.
  • Other document-level exception rules ($generichide, $elemhide or $jsinject modifiers) are applied alongside $replace rules. It means that you can modify the page content with a $replace rule and disable cosmetic rules there at the same time.

$replace value can be empty in the case of exception rules. See examples section for further information.

Multiple rules matching a single request

In case if multiple $replace rules match a single request, we will apply each of them. The order is defined alphabetically.

Syntax

In general, $replace syntax is similar to replacement with regular expressions in Perl.

replace = "/" regexp "/" replacement "/" modifiers
  • regexp — a regular expression.
  • replacement — a string that will be used to replace the string corresponding to regexp.
  • modifiers — a regular expression flags. For example, i — insensitive search, or s — single-line mode.

In the $replace value, two characters must be escaped: comma , and dollar sign $. Use backslash \ for it. For example, an escaped comma looks like this: \,.

Examples

||example.org^$replace=/(<VAST[\s\S]*?>)[\s\S]*<\/VAST>/\$1<\/VAST>/i

There are three parts in this rule:

  • regexp(<VAST(.|\s)*?>)(.|\s)*<\/VAST>;
  • replacement\$1<\/VAST> where $ is escaped;
  • modifiersi for insensitive search.

You can see how this rule works here: http://regexr.com/3cesk

Multiple $replace rules

  1. ||example.org^$replace=/X/Y/
  2. ||example.org^$replace=/Z/Y/
  3. @@||example.org/page/*$replace=/Z/Y/
  • Both rule 1 and 2 will be applied to all requests sent to example.org.
  • Rule 2 is disabled for requests matching ||example.org/page/, but rule 1 still works!

Disabling $replace rules

  • @@||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.
Restrictions

Rules with the $replace modifier can only be used in trusted filters.

Compatibility

Rules with $replace modifier are supported by AdGuard for Windows, AdGuard for Mac, AdGuard for 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.

$urltransform

The $urltransform rules allow you to modify the request URL by replacing text matched by a regular expression.

Features

  • $urltransform rules normally only apply to the path and query parts of the URL, see below for one exception.
  • $urltransform will not be applied if the original URL is blocked by other rules.
  • $urltransform will be applied before $removeparam rules.

The $urltransform value can be empty for exception rules.

Multiple rules matching a single request

If multiple $urltransform rules match a single request, we will apply each of them. The order is defined alphabetically.

Syntax

$urltransform syntax is similar to replacement with regular expressions in Perl.

urltransform = "/" regexp "/" replacement "/" modifiers
  • regexp — a regular expression.
  • replacement — a string that will be used to replace the string corresponding to regexp.
  • modifiers — a regular expression flags. For example, i — insensitive search, or s — single-line mode.

In the $urltransform value, two characters must be escaped: the comma , and the dollar sign $. Use the backslash character \ for this. For example, an escaped comma looks like this: \,.

Changing the origin

Compatibility

This section only applies to AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.17 or later.

As stated above, normally $urltransform rules are only allowed to change the path and query parts of the URL. However, if the rule's regexp begins with the string ^http, then the full URL is searched and can be modified by the rule. Such a rule will not be applied if the URL transformation can not be achieved via an HTTP redirect (for example, if the request's method is POST).

Examples

||example.org^$urltransform=/(pref\/).*\/(suf)/\$1\$2/i

There are three parts in this rule:

  • regexp(pref\/).*\/(suf);
  • replacement\$1\$2 where $ is escaped;
  • modifiersi for insensitive search.

Multiple $urltransform rules

  1. ||example.org^$urltransform=/X/Y/
  2. ||example.org^$urltransform=/Z/Y/
  3. @@||example.org/page/*$urltransform=/Z/Y/
  • Both rule 1 and 2 will be applied to all requests sent to example.org.
  • Rule 2 is disabled for requests matching ||example.org/page/, but rule 1 still works!

Re-matching rules after transforming the URL

After applying all matching $urltransform rules, the transformed request will be matched against all other rules:

E.g., with the following rules:

||example.com^$urltransform=/firstpath/secondpath/
||example.com/secondpath^

the request to https://example.com/firstpath will be blocked.

Disabling $urltransform rules

  • @@||example.org^$urltransform will disable all $urltransform rules matching ||example.org^.
  • @@||example.org^$urltransform=/Z/Y/ will disable the rule with $urltransform=/Z/Y/ for any request matching ||example.org^.

$urltransform rules can also be disabled by $document and $urlblock exception rules. But basic exception rules without modifiers do not do that. For example, @@||example.com^ will not disable $urltransform=/X/Y/ for requests to example.com, but @@||example.com^$urlblock will.

Restrictions

Rules with the $urltransform modifier can only be used in trusted filters.

Compatibility

Rules with the $urltransform modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.15 or later.

noop

noop modifier does nothing and can be used solely to increase rules' readability. It consists of a sequence of underscore characters (_) of arbitrary length and can appear in a rule as often as needed.

Examples

||example.com$_,removeparam=/^ss\\$/,_,image
||example.com$replace=/bad/good/,___,~third-party
Compatibility

Rules with noop modifier are not supported by AdGuard Content Blocker.

$empty (deprecated)

Deprecation notice

This modifier is deprecated in favor of the $redirect modifier. Rules with $empty are still supported and being converted into $redirect=nooptext now but the support shall be removed in the future.

Usually, blocked requests look like a server error to browser. If you use $empty modifier, AdGuard will emulate a blank response from the server with200 OK status.

Examples

  • ||example.org^$empty returns an empty response to all requests to example.org and all subdomains.
Compatibility

Rules with $empty modifier are not supported by AdGuard Content Blocker, AdGuard for iOS, and AdGuard for Safari.

$mp4 (deprecated)

Deprecation notice

This modifier is deprecated in favor of the $redirect modifier. Rules with $mp4 are still supported and being converted into $redirect=noopmp4-1s,media now but the support shall be removed in the future.

As a response to blocked request AdGuard returns a short video placeholder.

Examples

  • ||example.com/videos/$mp4 blocks all video downloads from ||example.com/videos/* and changes the response to a video placeholder.
Compatibility

Rules with $mp4 modifier are not supported by AdGuard Content Blocker, AdGuard for iOS, and AdGuard for Safari.

Rule priorities

Each rule has its own priority, which is necessary when several rules match the request and the filtering engine needs to select one of them. Priority is measured by a positive integer.

Collisions

When two rules with the same priority match the same request, the filter engine implementation determines which one is chosen.

info

The concept of rule priorities becomes increasingly important in light of Manifest V3, as the existing rules need to be converted to declarativeNetRequest rules.

Priority calculation

To calculate priority, we've categorized modifiers into different groups. These groups are ranked based on their priority, from lowest to highest. A modifier that significantly narrows the scope of a rule adds more weight to its total priority. Conversely, if a rule applies to a broader range of requests, its priority decreases.

It's worth noting that there are cases where a single-parameter modifier has a higher priority than multi-parameter ones. For instance, in the case of $domain=example.com|example.org, a rule that includes two domains has a slightly broader effective area than a rule with one specified domain, therefore its priority is lower.

The base priority of any rule is 1. If the calculated priority is a floating-point number, it will be rounded up to the smallest integer greater than or equal to the calculated priority.

Compatibility
  • The concept of priority has been introduced in TSUrlFilter v2.1.0 and CoreLibs v1.13. Before that AdGuard didn't have any special priority computation algorithm and collisions handling could be different depending on AdGuard product and version.
  • AdGuard for iOS, Safari, and AdGuard Content Blocker rely on the browsers implementation and they cannot follow the rules specified here.
nota

Modifier aliases (1p, 3p, etc.) are not included in these categories, however, they are utilized within the engine to compute the rule priority.

Basic modifiers, the presence of each adds 1 to the priority

Ao lidar com um domínio negado, aplicativo, método ou tipo de conteúdo, adicionamos 1 ponto pela existência do modificador em si, independentemente da quantidade de domínios ou tipos de conteúdo negados. Isto ocorre porque o escopo da regra já é infinitamente amplo. De forma simples, ao proibir vários domínios, tipos de conteúdo, métodos ou aplicativos, o escopo da regra se torna apenas minimamente menor.

Modificadores de tipo de conteúdo definidos, métodos definidos, cabeçalhos definidos, $all, $popup, exceções específicas

Todos os tipos de conteúdo válidos:

Isso também inclui regras que adicionam implicitamente todos os tipos de conteúdo:

Ou regras que implicitamente adicionam o modificador $document:

Ou algumas exceções específicas que adicionam implicitamente $document,subdocument:

Ou métodos permitidos via $method.

Ou regras com $header.

A presença de quaisquer modificadores de tipo de conteúdo adiciona (50 + 50 / N), onde N é o número de modificadores presentes, por exemplo: ||example.com^$image,script adicionará 50 + 50 / 2 = 50 + 25 = 75 ao peso total da regra.

The $all also belongs to this category, because it implicitly adds all content-type modifiers, e.g., $document,subdocument,image,script,media,<etc> + $popup.

O $popup também pertence a esta categoria porque adiciona implicitamente o modificador $document. Da mesma forma, exceções específicas adicionam $document,subdocument.

Se houver um modificador $method na regra com métodos permitidos, ele adiciona (50 + 50 / N), onde N é o número de métodos permitidos, por exemplo: ||example.com^$method=GET|POST|PUT adicionará 50 + 50 / 3 = 50 + 16,6 = 67 ao peso total da regra.

Se houver um modificador $header na regra, ele adiciona 50.

$domain ou $app com domínios ou aplicativos permitidos

Domínios especificados através de $domain ou aplicativos especificados através de $app adicionam 100 + 100 / N, onde N é o número de valores modificadores, por exemplo: ||example.com^$domain=example.com|example.org|example.net adicionará 100 + 100 / 3 = 134,3 = 135 ou ||example.com^$app=org.example.app1|org.example.app2 adicionará 100 + 100 / 2 = 151 ou ||example.com^$domain=example.com,app=org.example.app1|org.example.app2 adicionará 100 + 100/1 (parte $domain) e 100 + 100/2 (parte $app), totalizando 350.

Os valores do modificador que são expressões regulares ou tld serão interpretados como entradas normais do tipo example.com e contados um por um, por exemplo: ||example.com^$domain=example.* adicionarão 100 + 100 / 1 = 200 ou ||example.com^$domain=example.*|adguard.* adicionarão 100 + 100 / 2 = 150.

$redirect regras

Cada um deles adiciona 10^3 à prioridade da regra.

Exceções específicas

Cada um dos quais adiciona 10^4 à prioridade.

Assim como a exceção com $document modifier: porque é um alias para $elemhide,content,jsinject,urlblock,extensão. Ele adicionará 10^4 para cada modificador da lista superior, 10^4 * 5 no total.

Além disso, cada uma dessas exceções adiciona implicitamente os dois modificadores de tipo de conteúdo permitidos $document,subdocument.

Regras da lista de permissões

O modificador @@ adiciona 10^5 à prioridade da regra.

Regras $important

Modifier $important adds 10^6 to rule priority.

Rules for which there is no priority weight

Other modifiers, which are supposed to perform additional post- or pre-processing of requests, do not add anything to the rule priority.

nota

The $replace modifier takes precedence over all blocking rules of categories 1–3, as well as exception rules from categories 3–5, except $content, because an exception with the $content modifier overrides all $replace rules.

Examples

  1. ||example.com^

    Weight of the rule without modifiers: 1.

  2. ||example.com^$match-case

    Rule weight: base weight + weight of the modifier from category 1: 1 + 1 = 2.

  3. ||example.org^$removeparam=p

    Rule weight: base weight + 0, since $removeparam is not involved in the priority calculation: 1 + 0 = 1.

  4. ||example.org^$document,redirect=nooptext

    Rule weight: base weight + allowed content type, category 3 + $redirect from category 6: 1 + (100 + 100 / 1) + 1000 = 1201.

  5. @@||example.org^$removeparam=p,document

    Rule weight: base weight + allowlist rule, category 5 + 0 because $removeparam is not involved in the priority calculation + allowed content type, category 2: 1 + 10000 + 0 + (50 + 50 / 1) = 10101.

  6. @@||example.com/ad/*$domain=example.org|example.net,important

    Rule weight: base weight + allowlist rule, category 5 + important rule, category 7 + allowed domains, category 3: 1 + 10000 + 1000000 + (100 + 100 / 2) = 1010152.

  7. @@||example.org^$document without additional modifiers is an alias for @@||example.com^$elemhide,content,jsinject,urlblock,extension

    Rule weight: base weight + specific exceptions, category 4 + two allowed content types (document and subdocument), category 2: 1 + 10000 * 4 + (50 + 50 / 2) = 40076.

  8. *$script,domain=a.com,denyallow=x.com|y.com

    Rule weight: base weight + allowed content type, category 2 + allowed domain, category 3 + denyallow, category 1: 1 + (50 + 50/1) + (100 + 100 / 1) + 1 = 303.

  9. ||example.com^$all — alias to ||example.com^$document,subdocument,image,script,media,etc. + $popup

    Rule weight: base weight + popup (category 1) + allowed content types (category 2): 1 + 1 + (50 + 50/12) = 55.

Non-basic rules

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

Categories \ ProductsAplicativos do CoreLibsAdGuard for ChromiumAdGuard for Chrome MV3AdGuard for FirefoxAdGuard para iOSAdGuard para SafariBloqueador de conteúdo do AdGuard
Element hiding
CSS rules
Extended CSS
HTML filtering
JavaScript
Scriptlets
nota
  • ✅ — fully supported
  • ❌ — not supported

Regras cosméticas

info

Work with non-basic rules requires the basic knowledge of HTML and CSS. So, if you want to learn how to make such rules, we recommend to get acquainted with this documentation.

Element hiding rules

Element hiding rules are used to hide the elements of web pages. It is similar to applying { display: none; } style to selected element.

Element hiding rules may operate differently depending on the platform.

Syntax

   rule = [domains] "##" selector
domains = [domain0, domain1[, ...[, domainN]]]
  • selectorCSS selector, defines the elements to be hidden.
  • domains — domain restriction for the rule.

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.

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.

nota

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.

Examples

  • example.com##div.textad — hides a div with the class textad at example.com and all subdomains.
  • 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 the class textad at all domains, except example.com and its subdomains.

Limitações

O Safari não é compatível com domínios permitidos e não permitidos. Portanto, as regras como example.org,~foo.example.org##.textad são inválidas no AdGuard para Safari.

Exceptions

As exceções podem desativar algumas regras em domínios específicos. Elas são muito semelhantes às regras de exceção habituais, mas em vez de ## você deve usar #@#.

For example, there is a rule in filter:

##.textad

If you want to disable it for example.com, you can create an exception rule:

example.com#@#.textad

Sometimes, it may be necessary to disable all restriction rules. Por exemplo, para realizar testes. Para isso, use a regra de exclusão sem especificar um domínio. Ele desativará completamente a regra elemhide CSS correspondente em TODOS os domínios:

#@#.textad

O mesmo pode ser alcançado adicionando esta regra:

*#@#.textad

Recomendamos usar esse tipo de exceção somente se não for possível alterar a própria regra de ocultação. In other cases it is better to change the original rule, using domain restrictions.

Regras CSS

Às vezes, simplesmente ocultar um elemento não é suficiente para lidar com a publicidade. Por exemplo, bloquear um elemento de publicidade pode apenas quebrar o layout da página. Neste caso, o AdGuard pode usar regras que são muito mais flexíveis do que regras de ocultação. Com essas regras, você pode basicamente adicionar qualquer estilo CSS à página.

Syntax

   rule = [domains] "#$#" selector "{" style "}"
domains = [domain0, domain1[, ...[, domainN]]]
  • selectorCSS selector, that defines the elements we want to apply the style to.
  • domains — domain restriction for the rule. Os mesmos princípios que nas regras de ocultação de elementos.
  • style — estilo CSS que queremos aplicar aos elementos selecionados.

Examples

example.com#$#body { background-color: #333!important; }

This rule will apply a style background-color: #333!important; to the body element at example.com and all subdomains.

Exceptions

Assim como na ocultação de elementos, há um tipo de regras que desativam a regra de estilo CSS selecionada para domínios específicos. A sintaxe da regra de exceção é quase a mesma, você só precisa mudar #$# para #@$#.

For example, there is a rule in filter:

#$#.textad { visibility: hidden; }

If you want to disable it for example.com, you can create an exception rule:

example.com#@$#.textad { visibility: hidden; }

We recommend to use this kind of exceptions only if it is not possible to change the CSS rule itself. In other cases it is better to change the original rule, using domain restrictions.

Restrictions

Estilos que levam ao carregamento de qualquer recurso são proibidos. Basicamente, isso significa que você não pode usar nenhum valor do tipo <url> no estilo.

Compatibility

As regras CSS não são suportadas pelo Bloqueador de conteúdo AdGuard.

As regras de CSS podem operar de maneira diferente dependendo da plataforma.

Seletores CSS Estendidos

CSS 3.0 não é sempre suficiente para bloquear anúncios. Para resolver esse problema, o AdGuard estende as capacidades do CSS ao adicionar suporte para os novos pseudo-elementos. Desenvolvemos uma biblioteca de código aberto separada para seleção de elementos não padronizados e aplicação de estilos CSS com propriedades estendidas.

A ideia de capacidades estendidas é uma oportunidade de combinar elementos do DOM com seletores com base em sua própria representação (estilo, conteúdo de texto, etc.) ou relações com outros elementos. Há também uma oportunidade de aplicar estilos com propriedades CSS não padrão.

Área do aplicativo

Seletores Estendidos podem ser usados em qualquer regra cosmética, sejam elas regras de ocultação de elementos ou regras CSS.

Compatibility

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 force applying these rules by ExtendedCss. 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 rules, #@$?# — for exceptions

We strongly recommend using these markers any time when you use an extended CSS selector.

Examples

  • example.org#?#div:has(> a[target="_blank"][rel="nofollow"]) — this rule blocks all div elements containing a child node that has a link with the attributes [target="_blank"][rel="nofollow"]. The rule applies only to example.org and its subdomains.
  • example.com#$?#h3:contains(cookies) { display: none!important; } — this rule sets the style display: none!important to all h3 elements that contain the word cookies. The rule applies only to example.com and all its subdomains.
  • example.net#?#.banner:matches-css(width: 360px) — this rule blocks all .banner elements with the style property width: 360px. The rule applies only to example.net and its subdomains.
  • example.net#@?#.banner:matches-css(width: 360px) — this rule will disable the previous rule.

You can apply standard CSS selectors using the ExtendedCss library by using the rule marker #?#, e.g. #?#div.banner.

Learn more about how to debug extended selectors.

nota

Some pseudo-classes do not require selector before it. Still adding the universal selector * makes an extended selector easier to read, even though it has no effect on the matching behavior. So selector #block :has(> .inner) works exactly like #block *:has(> .inner), but the second one is more obvious.

Pseudo-class names are case-insensitive, e.g. :HAS() works as :has(). Still the lower-case names are used commonly.

ExtendedCss Limitations

  1. CSS comments and at-rules are not supported.

  2. Specific pseudo-class may have its own limitations: :has(), :xpath(), :nth-ancestor(), :upward(), :is(), :not(), and :remove().

Pseudo-classe :has()

Draft CSS 4.0 specification describes the :has() pseudo-class. Unfortunately, it is not yet supported by all popular browsers.

nota

Rules with the :has() pseudo-class must use the native implementation of :has() if they use ## marker and if it is possible, i.e. with no other extended selectors inside. To force applying of ExtendedCss rules with :has(), use #?#/#$?# marker explicitly.

Compatibility with other pseudo-classes

Synonyms :-abp-has() is supported by ExtendedCss for better compatibility.

Removal notice

:if() is no longer supported as a synonym for :has().

Syntax

[target]:has(selector)
  • target — optional, standard or extended CSS selector, can be skipped for checking any element
  • selector — required, standard or extended CSS selector

The pseudo-class :has() selects the target elements that fit to the selector. Also the selector can start with a combinator.

A selector list can be set in selector as well. In this case all selectors in the list are being matched for now. In the future it will be fixed for <forgiving-relative-selector-list> as argument.

:has() limitations

Usage of the :has() pseudo-class is restricted for some cases (2, 3):

  • disallow :has() inside the pseudos accepting only compound selectors;
  • disallow :has() after regular pseudo-elements.

Native :has() pseudo-class does not allow :has(), :is(), :where() inside :has() argument to avoid increasing the :has() invalidation complexity (case 1). But ExtendedCss did not have such limitation earlier and filter lists already contain such rules, so we have not added this limitation to ExtendedCss and allow to use :has() inside :has() as it was possible before. To use it, just force ExtendedCss usage by setting #?#/#$?# rule marker.

Native implementation does not allow any usage of :scope inside the :has() argument ([1], [2]). Still, there are some such rules in filter lists: div:has(:scope a) which we continue to support by simply converting them to div:has(> a), as it used to be done previously.

Examples

div:has(.banner) selects all div elements which include an element with the banner class:

<!-- HTML code -->
<div>Not selected</div>
<div>Selected
<span class="banner">inner element</span>
</div>

div:has(> .banner) selects all div elements which include an banner class element as a direct child of div:

<!-- HTML code -->
<div>Not selected</div>
<div>Selected
<p class="banner">child element</p>
</div>

div:has(+ .banner) selects all div elements preceding banner class element which immediately follows the div and both are children of the same parent:

<!-- HTML code -->
<div>Not selected</div>
<div>Selected</div>
<p class="banner">adjacent sibling</p>
<span>Not selected</span>

div:has(~ .banner) selects all div elements preceding banner class element which follows the div but not necessarily immediately and both are children of the same parent:

<!-- HTML code -->
<div>Not selected</div>
<div>Selected</div>
<span>Not selected</span>
<p class="banner">general sibling</p>

div:has(span, .banner) selects all div elements which include both span element and banner class element:

<!-- HTML code -->
<div>Not selected</div>
<div>Selected
<span>child span</span>
<p class="banner">child .banner</p>
</div>
Old syntax

Backward compatible syntax for :has() is supported but not recommended.

Pseudo-classe :contains()

The :contains() pseudo-class principle is very simple: it allows to select the elements that contain specified text or which content matches a specified regular expression. Regexp flags are supported.

nota

The :contains() pseudo-class uses the textContent element property for matching, not the innerHTML.

Compatibility with other pseudo-classes

Synonyms :-abp-contains() and :has-text() are supported for better compatibility.

Syntax

[target]:contains(match)
  • target — optional, standard or extended CSS selector, can be skipped for checking any element
  • match — required, string or regular expression for matching element textContent. Regular expression flags are supported.

Examples

For such DOM:

<!-- HTML code -->
<div>Not selected</div>
<div id="match">Selected as IT contains "banner"</div>
<div>Not selected <div class="banner"></div></div>

the element div#match can be selected by any of these extended selectors:

! plain text
div:contains(banner)

! regular expression
div:contains(/as .*banner/)

! regular expression with flags
div:contains(/it .*banner/gi)
nota

Only the div with id=match is selected because the next element does not contain any text, and banner is a part of code, not a text.

Old syntax

Backward compatible syntax for :contains() is supported but not recommended.

Pseudo-class :matches-css()

The :matches-css() pseudo-class allows to match the element by its current style properties. The work of the pseudo-class is based on using the Window.getComputedStyle() method.

Syntax

[target]:matches-css([pseudo-element, ] property: pattern)
  • target — optional, standard or extended CSS selector, can be skipped for checking any element
  • pseudo-element — optional, valid standard pseudo-element, e.g. before, after, first-line, etc.
  • property — required, a name of CSS property to check the element for
  • pattern — required, a value pattern that is using the same simple wildcard matching as in the basic URL filtering rules or a regular expression. For this type of matching, AdGuard always does matching in a case-insensitive manner. In the case of a regular expression, the pattern looks like /regexp/.

Special characters escaping and unescaping

For non-regexp patterns (,),[,] must be unescaped, e.g. :matches-css(background-image:url(data:*)).

For regexp patterns \ should be escaped, e.g. :matches-css(background-image: /^url\\("data:image\\/gif;base64.+/).

Examples

For such DOM:

<!-- HTML code -->
<style type="text/css">
#matched::before {
content: "Block me"
}
</style>
<div id="matched"></div>
<div id="not-matched"></div>

the div elements with pseudo-element ::before and with specified content property can be selected by any of these extended selectors:

! string pattern
div:matches-css(before, content: block me)

! string pattern with wildcard
div:matches-css(before, content: block*)

! regular expression pattern
div:matches-css(before, content: /block me/)
Restrictions

Regexp patterns do not support flags.

Compatibility

Obsolete pseudo-classes :matches-css-before() and :matches-css-after() are no longer recommended but still are supported for better compatibility.

Old syntax

Backward compatible syntax for :matches-css() is supported but not recommended.

Pseudo-classe :matches-attr()

The :matches-attr() pseudo-class allows selecting an element by its attributes, especially if they are randomized.

Syntax

[target]:matches-attr("name"[="value"])
  • target — optional, standard or extended CSS selector, can be skipped for checking any element
  • name — required, simple string or string with wildcard or regular expression for attribute name matching
  • value — optional, simple string or string with wildcard or regular expression for attribute value matching

Escaping special characters

For regexp patterns " and \ should be escaped, e.g. div:matches-attr(class=/[\\w]{5}/).

Examples

div:matches-attr("ad-link") selects the element div#target1:

<!-- HTML code -->
<div id="target1" ad-link="1random23-banner_240x400"></div>

div:matches-attr("data-*"="adBanner") seleciona o elemento div#target2:

<!-- HTML code -->
<div id="target2" data-1random23="adBanner"></div>

div:matches-attr(*unit*=/^click$/) seleciona o elemento div#target3:

<!-- HTML code -->
<div id="target3" random123-unit094="click"></div>

*:matches-attr("/.{5,}delay$/"="/^[0-9]*$/") seleciona o elemento #target4:

<!-- HTML code -->
<div>
<inner-random23 id="target4" nt4f5be90delay="1000"></inner-random23>
</div>
Restrictions

Padrões Regexp não são compatíveis com flags.

Pseudo-classe :matches-property()

A pseudo-classe :matches-property() permite selecionar um elemento correspondendo às suas propriedades.

Syntax

[target]:matches-property("name"[="value"])
  • target — optional, standard or extended CSS selector, can be skipped for checking any element
  • name — required, simple string or string with wildcard or regular expression for element property name matching
  • value — optional, simple string or string with wildcard or regular expression for element property value matching

Escaping special characters

For regexp patterns " and \ must be escaped, e.g. div:matches-property(prop=/[\\w]{4}/).

nota

Regexp patterns are supported in name for any property in chain, e.g. prop./^unit[\\d]{4}$/.type.

Examples

An element with such properties:

divProperties = {
id: 1,
check: {
track: true,
unit_2random1: true,
},
memoizedProps: {
key: null,
tag: 12,
_owner: {
effectTag: 1,
src: 'ad.com',
},
},
};

can be selected by any of these extended selectors:

div:matches-property(check.track)

div:matches-property("check./^unit_.{4,8}$/")

div:matches-property("check.unit_*"=true)

div:matches-property(memoizedProps.key="null")

div:matches-property(memoizedProps._owner.src=/ad/)
For filter maintainers

To check properties of a specific element, do the following:

  1. Inspect the page element or select it in Elements tab of browser DevTools
  2. Run console.dir($0) in Console tab
Restrictions

Regexp patterns do not support flags.

Pseudo-classe :xpath()

The :xpath() pseudo-class allows selecting an element by evaluating an XPath expression.

Syntax

[target]:xpath(expression)
  • target- optional, standard or extended CSS selector
  • expression — required, valid XPath expression
:xpath() limitations

target can be omitted so it is optional. For any other pseudo-class that would mean "apply to all DOM nodes", but in case of :xpath() it just means "apply to the whole document", and such applying slows elements selecting significantly. That's why rules like #?#:xpath(expression) are limited to looking inside the body tag. For example, rule #?#:xpath(//div[@data-st-area=\'Advert\']) is parsed as #?#body:xpath(//div[@data-st-area=\'Advert\']).

Extended selectors with defined target as any selector — *:xpath(expression) — can still be used but it is not recommended, so target should be specified instead.

Works properly only at the end of selector, except for pseudo-class :remove().

Examples

:xpath(//*[@class="banner"]) selects the element div#target1:

<!-- HTML code -->
<div id="target1" class="banner"></div>

:xpath(//*[@class="inner"]/..) selects the element div#target2:

<!-- HTML code -->
<div id="target2">
<div class="inner"></div>
</div>

Pseudo-classe :nth-ancestor()

The :nth-ancestor() pseudo-class allows to lookup the nth ancestor relative to the previously selected element.

subject:nth-ancestor(n)
  • subject — required, standard or extended CSS selector
  • n — required, number >= 1 and < 256, distance to the needed ancestor from the element selected by subject

Syntax

subject:nth-ancestor(n)
  • subject — required, standard or extended CSS selector
  • n — required, number >= 1 and < 256, distance to the needed ancestor from the element selected by subject
:nth-ancestor() limitations

The :nth-ancestor() pseudo-class is not supported inside the argument of the :not() pseudo-class.

Examples

For such DOM:

<!-- HTML code -->
<div id="target1">
<div class="child"></div>

<div id="target2">
<div>
<div>
<div class="inner"></div>
</div>
</div>
</div>
</div>

.child:nth-ancestor(1) selects the element div#target1, div[class="inner"]:nth-ancestor(3) selects the element div#target2.

Pseudo-classe :upward()

The :upward() pseudo-class allows to lookup the ancestor relative to the previously selected element.

Syntax

subject:upward(ancestor)
  • subject — required, standard or extended CSS selector
  • ancestor — required, specification for the ancestor of the element selected by subject, can be set as:
    • number >= 1 and < 256 for distance to the needed ancestor, same as :nth-ancestor()
    • standard CSS selector for matching closest ancestor
:upward() limitations

The :upward() pseudo-class is not supported inside the argument of the :not() pseudo-class.

Examples

For such DOM:

<!-- HTML code -->
<div id="target1" data="true">
<div class="child"></div>

<div id="target2">
<div>
<div>
<div class="inner"></div>
</div>
</div>
</div>
</div>

.inner:upward(div[data]) selects the element div#target1, .inner:upward(div[id]) selects the element div#target2, .child:upward(1) selects the element div#target1, .inner:upward(3) selects the element div#target2.

Pseudo-classe :remove() e pseudo-propriedade remover

Sometimes, it is necessary to remove a matching element instead of hiding it or applying custom styles. In order to do it, you can use the :remove() pseudo-class as well as the remove pseudo-property.

Pseudo-class :remove() can be placed only at the end of a selector.

Syntax

! pseudo-class
selector:remove()

! pseudo-property
selector { remove: true; }
  • selector — required, standard or extended CSS selector
:remove() and remove limitations

The :remove() pseudo-class is limited to work properly only at the end of selector.

For applying the :remove() pseudo-class to any element, the universal selector * should be used. Otherwise such extended selector may be considered as invalid, e.g. .banner > :remove() is not valid for removing any child element of banner class element, so it should look like .banner > *:remove().

If the :remove() pseudo-class or the remove pseudo-property is used, all style properties are ignored except for the debug pseudo-property.

Examples

div.banner:remove()
div:has(> div[ad-attr]):remove()

div:contains(advertisement) { remove: true; }
div[class]:has(> a > img) { remove: true; }
nota

Rules with the remove pseudo-property must use #$?# marker: $ for CSS-style rule syntax, ? for ExtendedCss syntax.

Pseudo-classe :is()

The :is() pseudo-class allows to match any element that can be selected by any of selectors passed to it. Invalid selectors are skipped and the pseudo-class deals with valid ones with no error thrown. Our implementation of the native :is() pseudo-class.

Syntax

[target]:is(selectors)
  • target — optional, standard or extended CSS selector, can be skipped for checking any element
  • selectorsforgiving selector list of standard or extended selectors. For extended selectors, only compound selectors are supported, not complex.
:is() limitations

Rules with the :is() pseudo-class must use the native implementation of :is() if rules use ## marker and it is possible, i.e. with no other extended selectors inside. To force applying ExtendedCss rules with :is(), use #?#/#$?# marker explicitly.

If the :is() pseudo-class argument selectors is an extended selector, due to the way how the :is() pseudo-class is implemented in ExtendedCss v2.0, it is impossible to apply it to the top DOM node which is html, i.e. #?#html:is(<extended-selectors>) does not work. So if target is not defined or defined as the universal selector *, the extended pseudo-class applying is limited to html's children, e.g. rules #?#:is(...) and #?#*:is(...) are parsed as #?#html *:is(...). Please note that there is no such limitation for a standard selector argument, i.e. #?#html:is(.locked) works fine.

Complex selectors with extended pseudo-classes are not supported as selectors argument for :is() pseudo-class, only compound ones are allowed. Check examples below for more details.

Examples

#container *:is(.inner, .footer) selects only the element div#target1:

<!-- HTML code -->
<div id="container">
<div data="true">
<div>
<div id="target1" class="inner"></div>
</div>
</div>
</div>

Due to limitations :is(*:not([class]) > .banner)' does not work but :is(*:not([class]):has(> .banner)) can be used instead of it to select the element div#target2:

<!-- HTML code -->
<span class="span">text</span>
<div id="target2">
<p class="banner">inner paragraph</p>
</div>

Pseudo-classe :not()

The :not() pseudo-class allows to select elements which are not matched by selectors passed as argument. Invalid argument selectors are not allowed and error is to be thrown. Our implementation of the :not() pseudo-class.

Syntax

[target]:not(selectors)
  • target — optional, standard or extended CSS selector, can be skipped for checking any element
  • selectors — list of standard or extended selectors
:not() limitations

Rules with the :not() pseudo-class must use the native implementation of :not() if rules use ## marker and it is possible, i.e. with no other extended selectors inside. To force applying ExtendedCss rules with :not(), use #?#/#$?# marker explicitly.

If the :not() pseudo-class argument selectors is an extended selector, due to the way how the :not() pseudo-class is implemented in ExtendedCss v2.0, it is impossible to apply it to the top DOM node which is html, i.e. #?#html:not(<extended-selectors>) does not work. So if target is not defined or defined as the universal selector *, the extended pseudo-class applying is limited to html's children, e.g. rules #?#:not(...) and #?#*:not(...) are parsed as #?#html *:not(...). Please note that there is no such limitation for a standard selector argument, i.e. #?#html:not(.locked) works fine.

The :not() is considered as a standard CSS pseudo-class inside the argument of the :upward() pseudo-class because :upward() supports only standard selectors.

"Up-looking" pseudo-classes which are :nth-ancestor() and :upward() are not supported inside selectors argument for :not() pseudo-class.

Examples

#container > *:not(h2, .text) selects only the element div#target1:

<!-- HTML code -->
<div id="container">
<h2>Header</h2>
<div id="target1"></div>
<span class="text">text</span>
</div>

Pseudo-classe :if-not() (excluída)

Removal notice

The :if-not() pseudo-class is removed and is no longer supported. Rules with it are considered as invalid.

This pseudo-class was basically a shortcut for :not(:has()). It was supported by ExtendedCss for better compatibility with some filters subscriptions.

Cosmetic rules priority

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 and CSS rules cannot override inline styles. In such cases, it is recommended to use extended selectors or HTML filtering.

In AdGuard Browser Extension, the so-called "user stylesheets" are used. They have higher priority than even the inline styles.

Extended CSS selectors use JavaScript to work and basically add an inline style themselves, therefore they can override any style.

Regras de filtragem HTML

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

HTML filtering rules are supported by AdGuard for Windows, AdGuard for Mac, AdGuard for 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.

Syntax

     selector = [tagName] [attributes] [pseudoClasses]
combinator = ">"
rule = [domains] "$$" selector *(combinator selector)
domains = [domain0, domain1[, ...[, domainN]]]
attributes = "[" name0 = value0 "]" "[" name1 = value2 "]" ... "[" nameN = valueN "]"
pseudoClasses = pseudoClass *pseudoClass
pseudoClass = ":" pseudoName [ "(" pseudoArgs ")" ]
  • tagName — name of the element in lower case, for example, div or script.
  • domains — domain restriction for the rule. Same principles as in element hiding rule syntax.
  • attributes — a list of attributes that limit the selection of elements. name — attribute name, value — substring, that is contained in attribute value.
  • pseudoName — the name of a pseudo-class.
  • pseudoArgs — the arguments of a function-style pseudo-class.
  • combinator — an operator that works similarly to the CSS child combinator: that is, the selector on the right of the combinator will only match an element whose direct parent matches the selector on the left of the combinator.

Examples

HTML code:

<script data-src="/banner.js"></script>

Rule:

example.org$$script[data-src="banner"]

This rule removes all script elements with the attribute data-src containing the substring banner. The rule applies only to example.org and all its subdomains.

Special attributes

In addition to usual attributes, which value is every element checked for, there is a set of special attributes that change the way a rule works. Below there is a list of these attributes:

tag-content

Deprecation notice

This special attribute may become unsupported in the future. Prefer using the :contains() pseudo-class where it is available.

This is the most frequently used special attribute. It limits selection with those elements whose innerHTML code contains the specified substring.

You must use "" to escape ", for instance: $$script[tag-content="alert(""this is ad"")"]

For example, take a look at this HTML code:

<script type="text/javascript">
document.write('<div>banner text</div>" />');
</script>

Following rule will delete all script elements with a banner substring in their code:

$$script[tag-content="banner"]
Limitations

The tag-content special attribute must not appear in a selector to the left of a > combinator.

wildcard

Deprecation notice

This special attribute may become unsupported in the future. Prefer using the :contains() pseudo-class where it is available.

This special attribute works almost like tag-content and allows you to check the innerHTML code of the document. Rule will check if HTML code of the element fits the search pattern.

You must use "" to escape ", for instance: $$script[wildcard=""banner""]

For example: $$script[wildcard="*banner*text*"]

It checks if the element code contains the two consecutive substrings banner and text.

Limitations

The wildcard special attribute must not appear in a selector to the left of a > combinator.

max-length

Deprecation notice

This special attribute may become unsupported in the future. Prefer using the :contains() pseudo-class with a regular expression where it is available.

Specifies the maximum length for content of HTML element. If this parameter is set and the content length exceeds the value, a rule does not apply to the element.

Default value

If this parameter is not specified, the max-length is considered to be 8192.

Por exemplo:

$$div[tag-content="banner"][max-length="400"]

This rule will remove all the div elements, whose code contains the substring banner and the length of which does not exceed 400 characters.

Limitations

The max-length special attribute must not appear in a selector to the left of a > combinator.

min-length

Deprecation notice

This special attribute may become unsupported in the future. Prefer using the :contains() pseudo-class with a regular expression where it is available.

Specifies the minimum length for content of HTML element. Se este parâmetro estiver definido e o comprimento do conteúdo for menor que o valor predefinido, uma regra não se aplica ao elemento.

Por exemplo:

$$div[tag-content="banner"][min-length="400"]

Esta regra irá remover todos os elementos div, cujo código contém a substring banner e cujo comprimento excede 400 caracteres.

Limitations

O atributo especial min-length não deve aparecer em um seletor à esquerda de um combinador >.

Pseudo-classes

:contains()

Syntax
:contains(unquoted text)

ou

:contains(/reg(ular )?ex(pression)?/)
Compatibility

:-abp-contains() e :has-text() são sinônimos para :contains().

Compatibility

A pseudoclasse :contains() é compatível com o AdGuard para Windows, Mac e Android com CoreLibs v1.13 ou posterior.

Requer que o HTML interno do elemento contenha o texto especificado ou corresponda à expressão regular especificada.

Limitations

Uma pseudo-classe :contains() não deve aparecer em um seletor à esquerda de um combinador >.

Exceptions

Assim como nas regras de ocultação, há um tipo especial de regras que desativam a regra de filtragem HTML selecionada para domínios específicos. A sintaxe é a mesma, você só precisa mudar $$ para $@$.

For example, there is a rule in filter:

$$script[tag-content="banner"]

If you want to disable it for example.com, you can create an exception rule:

example.com$@$script[tag-content="banner"]

Sometimes, it may be necessary to disable all restriction rules. Por exemplo, para realizar testes. Para isso, use a regra de exclusão sem especificar um domínio.

$@$script[tag-content="banner"]

Recomendamos usar esse tipo de exceção somente se não for possível alterar a própria regra de ocultação. In other cases it is better to change the original rule, using domain restrictions.

JavaScript rules

O AdGuard oferece um tipo especial de regras que permite injetar qualquer código JavaScript nas páginas dos sites.

Nós recomendamos fortemente o uso de scriptlets em vez de regras JavaScript sempre que possível. As regras do JS devem ajudar na depuração, mas como uma solução de longo prazo, uma regra de script deve ser usada.

Syntax

rule = [domains] "#%#" script
  • domains — restrição de domínio para a regra. Os mesmos princípios que nas regras de ocultação de elementos.
  • script — código JavaScript arbitrário em uma string.

Examples

  • example.org#%#window.__gaq = undefined; executes the code window.__gaq = undefined; on all pages at example.org and all subdomains.

Exceptions

Similar to hiding rules, there is a special type of rules that disable the selected JavaScript rule for particular domains. A sintaxe é a mesma, você só precisa mudar #%# para #@%#.

For example, there is a rule in filter:

#%#window.__gaq = undefined;

If you want to disable it for example.com, you can create an exception rule:

example.com#@%#window.__gaq = undefined;

Sometimes, it may be necessary to disable all restriction rules. Por exemplo, para realizar testes. Para isso, use a regra de exclusão sem especificar um domínio.

#@%#window.__gaq = undefined;

Recomendamos usar esse tipo de exceção somente se não for possível alterar a própria regra de ocultação. In other cases it is better to change the original rule, using domain restrictions.

Restrictions

As regras de JavaScript só podem ser usadas em filtros confiáveis.

Compatibility

As regras JavaScript não são compatíveis com o Bloqueador de conteúdo AdGuard.

Regras de scriptlets

Scriptlet é uma função JavaScript que fornece capacidades estendidas para bloqueio de conteúdo. Essas funções podem ser usadas de maneira declarativa nas regras de filtragem do AdGuard.

nota

AdGuard oferece suporte a muitos scriptlets diferentes. Para alcançar a compatibilidade entre bloqueadores, também oferecemos suporte à sintaxe do uBO e ABP.

Sintaxe das regras de bloqueio

[domains]#%#//scriptlet(name[, arguments])
  • domains — opcional, uma lista de domínios onde a regra deve ser aplicada;
  • name — required, a name of the scriptlet from the AdGuard Scriptlets library;
  • arguments — opcional, uma lista de string argumentos (nenhum outro tipo de argumento é suportado).

Examples

  1. Aplique o abort-on-property-read scriptlet em todas as páginas de example.org e seus subdomínios, e passe um argumento alert:

    example.org#%#//scriptlet('abort-on-property-read', 'alert')
  2. Remova a classe branding de todos os elementos div[class^="inner"] em todas as páginas de example.org e seus subdomínios:

    example.org#%#//scriptlet('remove-class', 'branding', 'div[class^="inner"]')

Sintaxe das regras de exceção

As regras de exceção podem desativar alguns scriptlets em domínios específicos. A sintaxe para regras de scriptlet de exceção é semelhante às regras normais de scriptlet, mas usa #@%# em vez de #%#:

[domains]#@%#//scriptlet([name[, arguments]])
  • domains — optional, a list of domains where the rule should be applied;
  • name — optional, a name of the scriptlet to except from the applying; if not set, all scriptlets will not be applied;
  • arguments — optional, a list of string arguments to match the same blocking rule and disable it.

Examples

  1. Desativar regra de scriptlet específica para que apenas abort-on-property-read seja aplicada somente em example.org e seus subdomínios:

    example.org,example.com#%#//scriptlet("abort-on-property-read", "alert")
    example.com#@%#//scriptlet("abort-on-property-read", "alert")
  2. Desativar todos os abort-on-property-read scriptlets para example.com e seus subdomínios:

    example.org,example.com#%#//scriptlet("abort-on-property-read", "alert")
    example.com#@%#//scriptlet("abort-on-property-read")
  3. Desativar todos os scriptlets para example.com e seus subdomínios:

    example.org,example.com#%#//scriptlet("abort-on-property-read", "alert")
    example.com#@%#//scriptlet()
  4. Aplique set-constant e set-cookie a qualquer página web, mas devido à regra de exceção de scriptlet especial apenas o scriptlet set-constant será aplicado em example.org e seus subdomínios:

    #%#//scriptlet('set-constant', 'adList', 'emptyArr')
    #%#//scriptlet('set-cookie', 'accepted', 'true')
    example.org#@%#//scriptlet('set-cookie')
  5. Apply adjust-setInterval to any web page and set-local-storage-item on example.com and its subdomains, but there are also multiple scriptlet exception rules, so no scriptlet rules will be applied on example.com and its subdomains:

    #%#//scriptlet('adjust-setInterval', 'count', '*', '0.001')
    example.com#%#//scriptlet('set-local-storage-item', 'ALLOW_COOKIES', 'false')
    example.com#@%#//scriptlet()

Learn more about how to debug scriptlets.

More information about scriptlets can be found on GitHub.

Compatibility

Scriptlet rules are not supported by AdGuard Content Blocker.

The full syntax of scriptlet exception rules is supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.16 or later, and AdGuard Browser Extension for Chrome, Firefox, and Edge with TSUrlFilter v3.0 or later. Previous versions only support exception rules that disable specific scriptlets.

Trusted scriptlets

Trusted scriptlets are scriptlets with extended functionality. It means the same syntax and restrictions. Trusted scriptlet names are prefixed with trusted-, e.g. trusted-set-cookie, to be easily distinguished from common scriptlets.

nota

Trusted scriptlets are not compatible with other ad blockers except AdGuard.

Restrictions

Trusted scriptlets rules can only be used in trusted filters.

Compatibility

Trusted scriptlets rules are not supported by AdGuard Content Blocker.

Learn more about how to debug scriptlets.

More information about trusted scriptlets can be found on GitHub.

Modifiers for non-basic type of rules

Each rule can be modified using the modifiers described in the following paragraphs.

Syntax {#non-basic-rules-modifiers-syntax}

rule = "[$" modifiers "]" [rule text]
modifiers = modifier0[, modifier1[, ...[, modifierN]]]
  • modifier — set of the modifiers described below.
  • rule text — a rule to be modified.

For example, [$domain=example.com,app=test_app]##selector.

In the modifiers values, the following characters must be escaped: [, ], ,, and \ (unless it is used for the escaping). Use \ to escape them. For example, an escaped bracket looks like this: \].

Modificador \ ProdutosAplicativos do CoreLibsAdGuard for ChromiumAdGuard for Chrome MV3AdGuard for FirefoxAdGuard para iOSAdGuard para SafariBloqueador de conteúdo do AdGuard
$app
$domain*[1]
$path
$url*[2]*[2]*[2]
nota
  • ✅ — fully supported
  • ✅ * — supported, but reliability may vary or limitations may occur; check the modifier description for more details
  • ❌ — not supported

$app

$app modifier lets you narrow the rule coverage down to a specific application or a list of applications. The modifier's behavior and syntax perfectly match the corresponding basic rules $app modifier.

Examples

  • [$app=org.example.app]example.com##.textad hides a div with the 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 the 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') applies scriptlet prevent-setInterval only in Safari browser on Mac.
  • [$app=org.example.app]#@#.textad disables all ##.textad rules for all domains while using org.example.app.
Compatibility

Such rules with $app modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android.

$domain

$domain modifier limits the rule application area to a list of domains and their subdomains. The modifier's behavior and syntax perfectly match the corresponding basic rules $domain modifier.

Examples

  • [$domain=example.com]##.textad — hides a div with the 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.

There are 2 ways to specify domain restrictions for non-basic rules:

  1. the "classic" way is to specify domains before rule mask and attributes: example.com##.textad;
  2. the modifier approach is to specify domains via $domain modifier: [$domain=example.com]##.textad.

But rules with mixed style domains restriction are considered invalid. So, for example, the rule [$domain=example.org]example.com##.textad will be ignored.

Non-basic $domain modifier limitations

Limitations

Since the non-basic $domain works the same as the basic one, it has the same limitations.

Compatibility

Such rules with $domain modifier are supported by AdGuard for Windows, AdGuard for Mac, AdGuard for Android, AdGuard Browser Extension for Chrome, Chrome MV3, Firefox, and Edge.

$path

$path modifier limits the rule application area to specific locations or pages on websites.

Syntax

$path ["=" pattern]

pattern — optional, a path mask to which the rule is restricted. Its syntax and behavior are pretty much the same as with the pattern for basic rules. You can also use special characters, except for ||, which does not make any sense in this case (see examples below).

If pattern is not set for $path, rule will apply only on the main page of website.

$path modifier matches the query string as well.

$path modifier supports regular expressions in the same way basic rules do.

Examples

  • [$path=page.html]##.textad hides a div with the 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 the 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 the class textad at /page.html or /page.html?<query> of any domain but not at /sub/page.html
  • [$path=/page.html|]##.textad hides a div with the class textad at /page.html or /sub/page.html of any domain but not at /page.html?<query>
  • [$path=/page*.html]example.com##.textad hides a div with the class textad at /page1.html or /page2.html or any other path matching /page<...>.html of example.com
  • [$path]example.com##.textad hides a div with the class textad at the main page of example.com
  • [$domain=example.com,path=/page.html]##.textad hides a div with the 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 the class textad at both /sub1/page.html and /sub2/page.html of any domain (please note the escaped special characters)
Compatibility

Rules with $path modifier are not supported by AdGuard Content Blocker.

$url

$url modifier limits the rule application area to URLs matching the specified mask.

Syntax

url = pattern

where pattern is pretty much the same as pattern of the basic rules assuming that some characters must be escaped. The special characters and regular expressions are supported as well.

Examples

  • [$url=||example.com/content/*]##div.textad hides a div with the class textad at addresses like https://example.com/content/article.html and even https://subdomain.example.com/content/article.html.
  • [$url=||example.org^]###adblock hides an element with attribute id equal to adblock at example.org and its subdomains.
  • [$url=/\[a-z\]+\\.example\\.com^/]##.textad hides div elements of the class textad for all domains matching the regular expression [a-z]+\.example\.com^.

$url modifier limitations

Limitations

In AdGuard Browser Extension, non-basic $url modifier is not compatible with domain-specific rules and other non-basic modifiers — $domain and $path. For example, the rule [$url=/category/*]example.com###textad will not be applied.

Compatibility

Rules with the $url modifier are supported by AdGuard for Windows, AdGuard for Mac, and AdGuard for Android with CoreLibs v1.11 or later, and AdGuard Browser Extension with TSUrlFilter v3.0.0 or later.

Information for filter maintainers

If you maintain a third-party filter that is known to AdGuard, you might be interested in the information presented in this section. Please note that hints will be applied to registered filters only. The filter is considered to be registered and known by AdGuard, if it is present in the known filters index. If you want your filter to be registered, please file an issue to AdguardFilters repo.

Preprocessor directives

We provide preprocessor directives that can be used by filter maintainers to improve compatibility with different ad blockers and provide:

nota

Any mistake in a preprocessor directive will lead to AdGuard failing the filter update in the same way as if the filter URL was unavailable.

Preprocessor directives can be used in the user rules or in the custom filters.

Including a file

The !#include directive allows to include contents of a specified file into the filter. It supports only files from the same origin to make sure that the filter maintainer is in control of the specified file. The included file can also contain pre-directives (even other !#include directives). Ad blockers should consider the case of recursive !#include and implement a protection mechanism.

Syntax

!#include file_path

where file_path is a same origin absolute or relative file path to be included.

The files must originate from the same domain, but may be located in a different folder.

If included file is not found or unavailable, the whole filter update should fail.

Same-origin limitation should be disabled for local custom filters.

Examples

Filter URL: https://example.org/path/filter.txt

! Valid (same origin):
!#include https://example.org/path/includedfile.txt
!
! Valid (relative path):
!#include /includedfile.txt
!#include ../path2/includedfile.txt
!
! Invalid (another origin):
!#include https://domain.com/path/includedfile.txt

Conditions

Filter maintainers can use conditions to supply different rules depending on the ad blocker type. A conditional directive beginning with an !#if directive must explicitly be terminated with an !#endif directive. Conditions support all basic logical operators.

There are two possible scenarios:

  1. When an ad blocker encounters an !#if directive and no !#else directive, it will compile the code between !#if and !#endif directives only if the specified condition is true.

  2. If there is an !#else directive, the code between !#if and !#else will be compiled if the condition is true; otherwise, the code between !#else and !#endif will be compiled.

nota

Whitespaces matter. !#if is a valid directive, while !# if is not.

Syntax

!#if (conditions)
rules_list
!#endif

ou

!#if (conditions)
true_conditions_rules_list
!#else
false_conditions_rules_list
!#endif

where:

  • !#if (conditions) — start of the block when conditions are true
  • conditions — just like in some popular programming languages, preprocessor conditions are based on constants declared by ad blockers. Authors of ad blockers define on their own what exact constants they declare. Possible values:
    • adguard always declared; shows maintainers that this is one of AdGuard products; should be enough in 95% of cases
    • product-specific constants for cases when you need a rule to work (or not work — then ! should be used before constant) in a specific product only:
      • adguard_app_windows — AdGuard for Windows
      • adguard_app_mac — AdGuard for Mac
      • adguard_app_android — AdGuard for Android
      • adguard_app_ios — AdGuard for iOS
      • adguard_ext_safari — AdGuard for Safari
      • adguard_ext_chromium — AdGuard Browser Extension for Chrome (and chromium-based browsers, e.g. new Microsoft Edge)
      • adguard_ext_chromium_mv3AdGuard for Chrome MV3
      • adguard_ext_firefox — AdGuard Browser Extension for Firefox
      • adguard_ext_edge — AdGuard Browser Extension for Edge Legacy
      • adguard_ext_opera — AdGuard Browser Extension for Opera
      • adguard_ext_android_cb — AdGuard Content Blocker for mobile Samsung and Yandex browsers
      • ext_ublock — special case; this one is declared when a uBlock version of a filter is compiled by the FiltersRegistry
      • cap_html_filtering — products that support HTML filtering rules: AdGuard for Windows, AdGuard for Mac, and AdGuard for Android
  • !#else — start of the block when conditions are false
  • rules_list, true_conditions_rules_list, false_conditions_rules_list — lists of rules
  • !#endif — end of the block

Examples

! for all AdGuard products except AdGuard for Safari
!#if (adguard && !adguard_ext_safari)
||example.org^$third-party
domain.com##div.ad
!#endif
! directives even can be combined
!#if (adguard_app_android)
!#include /androidspecific.txt
!#endif
!#if (adguard && !adguard_ext_safari)
! for all AdGuard products except AdGuard for Safari
||example.org^$third-party
domain.com##div.ad
!#else
! for AdGuard for Safari only
||subdomain.example.org^$third-party
!#endif
Compatibility

The !#else directive is supported by the FiltersDownloader v1.1.20 or later.

It is already supported for filter lists compiled by the FiltersRegistry, but it still may not be supported by AdGuard products when adding a filter list with !#else as a custom one. The following products will support it in the mentioned versions or later:

  • AdGuard for Windows, Mac, and Android with CoreLibs v1.13;
  • AdGuard Browser Extension v4.2.208;
  • AdGuard v1.11.16 for Safari.

Safari affinity

Safari's limit for each content blocker is 150,000 active rules. But in AdGuard for Safari and AdGuard for iOS, we've split the rules into 6 content blockers, thus increasing the rule limit to 900,000.

Here is the composition of each content blocker:

  • AdGuard General — Ad Blocking, Language-specific
  • AdGuard Privacy — Privacy
  • AdGuard Social — Social Widgets, Annoyances
  • AdGuard Security — Security
  • AdGuard Other — Other
  • AdGuard Custom — Custom

User rules and allowlist are added to every content blocker.

:::cuidado

The main disadvantage of using multiple content blockers is that rules from different blockers are applied independently. Blocking rules are not affected by this, but unblocking rules may cause problems. If a blocking rule is in one content blocker and an exception is in another, the exception will not work. Filter maintainers use !#safari_cb_affinity to define Safari content blocker affinity for the rules inside of the directive block.

:::

Syntax

!#safari_cb_affinity(content_blockers)
rules_list
!#safari_cb_affinity

where:

  • !#safari_cb_affinity(content_blockers) — start of the block
  • content_blockers — comma-separated list of content blockers. Possible values:
    • general — AdGuard General content blocker
    • privacy — AdGuard Privacy content blocker
    • social — AdGuard Social content blocker
    • security — AdGuard Security content blocker
    • other — AdGuard Other content blocker
    • custom — AdGuard Custom content blocker
    • all — special keyword that means that the rules must be included into all content blockers
  • rules_list — list of rules
  • !#safari_cb_affinity — end of the block

Examples

! to unhide specific element which is hidden by AdGuard Base filter:
!#safari_cb_affinity(general)
example.org#@#.adBanner
!#safari_cb_affinity
! to allowlist basic rule from AdGuard Tracking Protection filter:
!#safari_cb_affinity(privacy)
@@||example.org^
!#safari_cb_affinity

Hints

"Hint" is a special comment, instruction to the filters compiler used on the server side (see FiltersRegistry).

Syntax

!+ HINT_NAME1(PARAMS) HINT_NAME2(PARAMS)

Multiple hints can be applied.

NOT_OPTIMIZED hint

For each filter, AdGuard compiles two versions: full and optimized. Optimized version is much more lightweight and does not contain rules which are not used at all or used rarely.

Rules usage frequency comes from the collected filter rules statistics. But filters optimization is based on more than that — some filters have specific configuration. This is how it looks like for Base filter:

"filter": AdGuard Base filter,
"percent": 30,
"minPercent": 20,
"maxPercent": 40,
"strict": true

where:

  • filter — filter identifier
  • percent — expected optimization percent ~= (rules count in optimized filter) / (rules count in original filter) * 100
  • minPercent — lower bound of percent value
  • maxPercent — upper bound of percent value
  • strict — if percent < minPercent OR percent > maxPercent and strict mode is on then filter compilation should fail, otherwise original rules must be used

In other words, percent is the "compression level". For instance, for the Base filter it is configured to 40%. It means that optimization algorithm should strip 60% of rules.

Eventually, here are the two versions of the Base filter for AdGuard Browser Extension:

If you want to add a rule which should not be removed at optimization use the NOT_OPTIMIZED hint:

!+ NOT_OPTIMIZED
||example.org^

And this rule will not be optimized only for AdGuard for Android:

!+ NOT_OPTIMIZED PLATFORM(android)
||example.org^

PLATFORM and NOT_PLATFORM hints

Used to specify the platforms to apply the rules. List of existing platforms and links to Base filter, for example, for each of them:

Examples

This rule will be available only in AdGuard for Windows, Mac, Android:

!+ PLATFORM(windows,mac,android)
||example.org^

Except for AdGuard for Safari, AdGuard Content Blocker, and AdGuard for iOS, this rule is available on all platforms:

!+ NOT_PLATFORM(ext_safari, ext_android_cb, ios)
||example.org^

How to debug filtering rules

It may be possible to create simple filtering rules "in your head" but for anything even slightly more complicated you will need additional tools to debug and iterate them. There are tools to assist you with that. You can use DevTools in Chrome and its analogs in other browsers but most AdGuard products provide another one — Filtering log.

Filtering log

Filtering log is an advanced tool that will be helpful mostly to filter developers. It lists all web requests that pass through AdGuard, gives you exhaustive information on each of them, offers multiple sorting options, and has other useful features.

Depending on which AdGuard product you are using, Filtering log can be located in different places.

  • In AdGuard for Windows, you can find it in the Ad Blocker tab or via the tray menu
  • In AdGuard for Mac, it is located in Settings → Advanced → Filtering log
  • In AdGuard for Android, you can find it under Statistics → Recent activity. Recent activity can also be accessed from the Assistant
  • In AdGuard Browser Extension, it is accessible from the Miscellaneous settings tab or by right-clicking the extension icon. Only Chromium- and Firefox-based web browsers show applied element hiding rules (including CSS, ExtCSS) and JS rules and scriptlets in their Filtering logs
nota

In AdGuard for iOS and AdGuard for Safari, Filtering log does not exist because of the way content blockers are implemented in Safari. AdGuard does not see the web requests and therefore cannot display them.

Selectors debugging mode

Sometimes, you might need to check the performance of a given selector or a stylesheet. In order to do it without interacting with JavaScript directly, you can use a special debug style property. When ExtendedCss meets this property, it enables the debugging mode either for a single selector or for all selectors, depending on the debug value.

Open the browser console while on a web page to see the timing statistics for selector(s) that were applied there. Debugging mode displays the following stats as object where each of the debugged selectors are keys, and value is an object with such properties:

Always printed:

  • selectorParsed — text of the parsed selector, may differ from the input one
  • timings — list of DOM nodes matched by the selector
    • appliesCount — total number of times that the selector has been applied on the page
    • appliesTimings — time that it took to apply the selector on the page, for each of the instances that it has been applied (in milliseconds)
    • meanTiming — mean time that it took to apply the selector on the page
    • standardDeviation — standard deviation
    • timingsSum — total time it took to apply the selector on the page across all instances

Printed only for remove pseudos:

  • removed — flag to signal if elements were removed

Printed if elements are not removed:

  • matchedElements — list of DOM nodes matched by the selector
  • styleApplied — parsed rule style declaration related to the selector

Examples

Debugging a single selector:

When the value of the debug property is true, only information about this selector will be shown in the browser console.

#$?#.banner { display: none; debug: true; }

Enabling global debug:

When the value of the debug property is global, the console will display information about all extended CSS selectors that have matches on the current page, for all the rules from any of the enabled filters.

#$?#.banner { display: none; debug: global; }

Testing extended selectors without AdGuard

ExtendedCss can be executed on any page without using any AdGuard product. In order to do that you should copy and execute the following code in a browser console:

!function(e,t,d){C=e.createElement(t),C.src=d,C.onload=function(){alert("ExtendedCss loaded successfully")},s=e.getElementsByTagName(t)[0],s?s.parentNode.insertBefore(C,s):(h=e.getElementsByTagName("head")[0],h.appendChild(C))}(document,"script","https://AdguardTeam.github.io/ExtendedCss/extended-css.min.js");

Alternatively, install the ExtendedCssDebugger userscript.

Now you can now use the ExtendedCss from global scope, and run its method query() as Document.querySelectorAll().

Examples

const selector = 'div.block:has=(.header:matches-css(after, content: Ads))';

// array of HTMLElements matched the `selector` is to be returned
ExtendedCss.query(selector);

Debugging scriptlets

If you are using AdGuard Browser Extension and want to debug a scriptlet or a trusted scriptlet rule, you can get additional information by opening the Filtering log. In that case, scriptlets will switch to debug mode and there will be more information in the browser console.

The following scriptlets are especially developed for debug purposes:

The following scriptlets also may be used for debug purposes:

Compatibility tables legend

Product shortcuts

  1. CoreLibs appsAdGuard for Windows, AdGuard for Mac, and AdGuard for Android
  2. AdGuard for ChromiumAdGuard Browser Extension for Chrome and other Chromium-based browsers such as Microsoft Edge and Opera
  3. AdGuard for Chrome MV3AdGuard Browser Extension for Chrome MV3
  4. AdGuard for FirefoxAdGuard Browser Extension for Firefox
  5. AdGuard for iOSAdGuard for iOS and AdGuard Pro for iOS (for mobile Safari browser)
  6. AdGuard for SafariAdGuard for desktop Safari browser
  7. AdGuard Content BlockerContent Blocker for Android mobile browsers: Samsung Internet and Yandex Browser

Compatibility shortcuts

nota
  • ✅ — fully supported
  • ✅ * — supported, but reliability may vary or limitations may occur; check the modifier description for more details
  • 🧩 — may already be implemented in nightly or beta versions but is not yet supported in release versions
  • ⏳ — recurso que está planejado para ser implementado, mas ainda não está disponível em nenhum produto
  • ❌ — not supported
  • 👎 — deprecated; still supported but will be removed in the future
  • 🚫 — removed and no longer supported