Extensões
Userscripts
Userscripts (também chamados de "extensões") são, na verdade, miniprogramas escritos em JavaScript. Eles modificam ou ampliam a funcionalidade de um ou mais websites. Muitos usuários do AdGuard já podem estar familiarizados com scripts de usuário como o Assistente AdGuard, o Bloqueador de pop-ups e o AdGuard Extra.
O AdGuard pode ampliar significativamente a funcionalidade de sites, agindo como um gerenciador de userscripts. Você pode adicionar seus scripts personalizados ou gerenciar os existentes em nossos três produtos: AdGuard para Windows, AdGuard para Android e AdGuard para Mac.
Scripts recomendados do AdGuard
Esses scripts de usuário vêm diretamente dos desenvolvedores do AdGuard e podemos garantir que são eficazes e seguros. Para alguns dos userscripts desenvolvidos por terceiros que consideramos bons e confiáveis, role para baixo até a próxima seção. Você também pode encontrar alguns dos sites populares com scripts abaixo, mas lembre-se de que sempre que você baixa um userscript de uma fonte desconhecida, você se expõe a um certo risco, pois alguns scripts podem ser prejudiciais para o seu computador.
AdGuard Extra
Uma extensão que bloqueia anúncios em casos difíceis, quando a abordagem usual baseada em filtros não é suficiente. O AdGuard Extra vem pré-instalado nos aplicativos autônomos do AdGuard, exceto no AdGuard para iOS, então você não precisa fazer nada para ativá-lo. No entanto, se quiser usá-lo junto com a extensão do navegador AdGuard ou qualquer outro bloqueador de anúncios, você precisará usar uma extensão adicional. Saiba mais sobre este userscript e como instalá-lo em GitHub.
Bloqueador de pop-ups do AdGuard
O nome fala por si: ele bloqueia pop-ups, um dos tipos mais irritantes de anúncios em sites. Saiba mais sobre este userscript, seus recursos principais e a sua instalação no GitHub.
Assistente AdGuard (versão antiga)
Esta extensão personalizada foi projetada para controlar a filtragem diretamente da página do navegador (bloqueio manual, exclusão de permitidos etc.).
Essa versão do Assistente é antiga e não faz sentido usá-la em novos sistemas, pois foi substituída pelo Assistente de navegador. Mas o Assistente antigo pode ser útil se não houver um Assistente de navegador para o seu navegador. Se este for o seu caso, você pode aprender como instalar o Assistente AdGuard no GitHub.
Disable AMP
Um script pré-instalado apenas no AdGuard para Android. Ele desativa o AMP (Accelerated Mobile Pages) na página de resultados de pesquisa do Google. Saiba mais sobre este userscript e como instalá-lo no GitHub.
Principais opções fora do AdGuard
Esses userscripts não são desenvolvidos pela AdGuard e, portanto, não podemos dar 100% de garantia de que eles são seguros e/ou funcionam em todos os momentos. No entanto, de acordo com a nossa experiência, eles merecem uma recomendação, pois todos conquistaram uma boa reputação.
Don't track me Google
Este script remove o recurso de rastreamento do Google dos links nos resultados de pesquisa do Google. Ele acelera o carregamento dos resultados da pesquisa e permite clicar com o botão direito ou tocar para copiar o link do URL.
O código-fonte está disponível no GitHub. Este userscript pode ser baixado no GreasyFork e instalado em qualquer aplicativo baseado em AdGuard CoreLibs.
tinyShield
Um userscripts para pessoas que visitam sites coreanos e alguns sites internacionais. O userscript do tinyShield bloqueia anúncios do Ad-Shield e anti-adblocks. Este userscript pode ser instalado em aplicativos baseados no CoreLibs do AdGuard, Violentmonkey, Tampermonkey e quoid/userscripts. Saiba mais sobre o tinyShield e como instalá-lo no GitHub.
Onde obter mais userscripts?
Como os userscripts são criados principalmente por entusiastas, você deve ter cuidado ao instalá-los. Qualquer script de fonte desconhecida acarreta um risco potencial. No entanto, há uma grande variedade de scripts interessantes que, se instalados com cuidado e responsabilidade, podem realmente tornar o uso de alguns sites mais conveniente.
Aqui descreveremos alguns dos catálogos de userscript mais populares.
Userscript.Zone
Userscript.Zone é um site que permite a busca por userscripts inserindo uma URL ou domínio correspondente. O site é fácil de usar e tem um alto nível de credibilidade, já que apenas scripts de páginas moderadas são exibidos.
Greasy Fork
Greasy Fork é um catálogo de userscripts dos criadores do Stylish. Os scripts neste catálogo passam por moderação, então sua credibilidade é muito maior.
OpenUserJS.org
OpenUserJS.org é um catálogo de userscripts de código aberto escrito em nodeJS. Não é moderado, então fique atento a scripts suspeitos.
Comunidade
Se você gosta da ideia de personalizar seu navegador com userscripts e tem alguma dúvida, pode perguntar em um destes sites:
Desenvolvimento
Solicitar licença
Se você está desenvolvendo seu próprio userscript e quer testar como ele funciona com o AdGuard, pode solicitar uma licença preenchendo o formulário.
Compatibilidade
Bloqueio de metadados
Propriedades compatíveis
@name
@namespace
@description
@version
@match
@include
@exclude
@grant
@connect
@require
@resource
@downloadURL
@updateURL
@homepage
,@homepageURL
,@source
,@website
@run-at
@noframes
@icon
,@iconURL
,@defaulticon
@icon64
,@icon64URL
Propriedades não compatíveis
Essas propriedades serão simplesmente ignoradas pelo AdGuard.
Funções GM compatíveis
O AdGuard oferece suporte às antigas funções GM_ e à nova API GM4 que usa o objeto GM.
Todas as funções antigas do Greasemonkey listadas estão obsoletas, mas ainda são suportadas.
GM.info
,GM_info
GM.setValue
,GM_setValue
GM.getValue
,GM_getValue
GM.listValues
,GM_listValues
GM.deleteValue
,GM_deleteValue
GM.getResourceUrl
,GM_getResourceURL
GM.setClipboard
,GM_setClipboard
GM.xmlHttpRequest
,GM_xmlhttpRequest
GM.openInTab
,GM_openInTab
GM.notification
unsafeWindow
GM_getResourceText
GM_addStyle
GM_log
GM.addElement
,GM_addElement
window.onurlchange
Você pode encontrar mais informações sobre a API do Greasemonkey em seu manual.
Exemplo
// ==UserScript==
// @name Name as shown to the user when locale is english or unknown
// @name:ru Name as shown to the user when locale is russian
// @description Description as shown to the user when locale is english or unknown
// @description:ru Description as shown to the user when locale is russian
// @icon https://myhomepage.com/myuserscript.png
// @version 1.0.0.0
// @downloadURL https://dl.myhomepage.org/myuserscript.user.js
// @updateURL https://dl.myhomepage.org/myuserscript.meta.js
// @homepageURL https://myhomepage.com/myuserscript
// @include *
// @exclude *://website.com/*
// @resource https://myhomepage.com/myuserscript.css
// @require https://myhomepage.com/mylibrary.js
// @grant property:settings
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_listValues
// @grant GM_getResourceText
// @grant GM_getResourceURL
// @grant GM_addStyle
// @grant GM_log
// @grant GM_setClipboard
// @grant GM_xmlhttpRequest
// @grant unsafeWindow
// @grant GM_info
// @grant GM_openInTab
// @grant GM_registerMenuCommand
// @grant GM_addElement
// @grant window.onurlchange
// @run-at document-start
// ==/UserScript==
!function(){(
console.log("I am loaded!");
)}();
Trusted Types API
AdGuard oferece uma instância da classe PolicyApi
que permite gerenciar Trusted Types em seus scripts de usuário.
Você pode acessar a instância desta classe usando a variável ADG_policyApi
em seu scripts de usuário.
Propriedades
name: string
— um nome da política (O padrão é"AGPolicy"
).isSupported: boolean
— um sinalizador que indica se a Trusted Types API é suportada pelo navegador atual.
Métodos polyfill
ADG_policyApi.createHTML
. Se não for suportado, retornainput: string
.ADG_policyApi.createScript
. Se não for suportado, retornainput: string
.ADG_policyApi.createScriptURL
. Se não for suportado, retornainput: string
.ADG_policyApi.getAttributeType
. Se não for suportado, retornanull
.ADG_policyApi.getPropertyType
. Se não for suportado, retornanull
.ADG_policyApi.isHTML
. Se não for suportado, retornafalse
.ADG_policyApi.isScript
. Se não for suportado, retornafalse
.ADG_policyApi.isScriptURL
. Se não for suportado, retornafalse
.
Tipos adicionais
/**
* Enum representation of the return values of the `getAttributeType` and
* `getPropertyType` methods of the native Trusted Types API.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicyFactory/getAttributeType}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicyFactory/getPropertyType}
*/
enum TrustedType {
HTML = 'TrustedHTML',
Script = 'TrustedScript',
ScriptURL = 'TrustedScriptURL',
}
// You can access it like that inside of userscript
ADG_TrustedType.HTML // "TrustedHTML"
/**
* Isomorphic trusted value type. If a browser supports the Trusted Types API, it will be one of the enum Trusted Types
* (`TrustedHTML`, `TrustedScript` or `TrustedScriptURL`); otherwise, it will be regular `string`.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedHTML}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedScript}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedScriptURL}
*/
type TrustedValue = string | TrustedHTML | TrustedScript | TrustedScriptURL;
Métodos adicionais
/**
* Creates a Trusted Type depending on `type`:
* - `TrustedHTML`
* - `TrustedScript`
* - `TrustedScriptURL`
* - or returns `value` if none of them is applicable.
*
* @param type Trusted Type.
* @param value Value from which a Trusted Type is created.
* @param createArgs Additional arguments to be passed to the function represented by `TrustedTypePolicy`.
* @returns Created value.
*/
function create(
type: TrustedType,
value: string,
...createArgs: unknown[]
): TrustedValue
// Example: Creates TrustedHTML
const trustedHTML = ADG_policyApi.create(ADG_TrustedType.HTML, '<div></div>');
/**
* Converts `value` of `attribute` into one of the Trusted Types:
* - `TrustedHTML`
* - `TrustedScript`
* - `TrustedScriptURL`
* - or returns `value` if none of them is applicable.
*
* @param tagName Name of an HTML tag.
* @param attribute Attribute.
* @param value Value of an attribute to be converted.
* @param elementNS Element namespace. If empty, defaults to the HTML namespace.
* @param attrNS Attribute namespace. If empty, defaults to null.
* @param createArgs Additional arguments to be passed to the function represented by `TrustedTypePolicy`.
* @returns Converted value.
*/
function convertAttributeToTrusted(
tagName: string,
attribute: string,
value: string,
elementNS?: string,
attrNS?: string,
...createArgs: unknown[]
): TrustedValue
// Example: Converts to TrustedScriptURL
const trustedScriptURL = ADG_policyApi.convertAttributeToTrusted("script", "src", 'SOME_URL');
scriptElement.setAttribute("src", trustedScriptURL);
/**
* Converts `value` of `property` into one of the Trusted Types:
* - `TrustedHTML`
* - `TrustedScript`
* - `TrustedScriptURL`
* - or returns `value` if none of them is applicable.
*
* @param tagName Name of an HTML tag.
* @param property Property.
* @param value Value of a property to be converted.
* @param elementNS Element namespace. If empty, defaults to the HTML namespace.
* @param createArgs Additional arguments to be passed to the function represented by `TrustedTypePolicy`.
* @returns Converted value.
*/
function convertPropertyToTrusted(
tagName: string,
property: string,
value: string,
elementNS?: string,
...createArgs: unknown[]
): TrustedValue
// Example: Converts to TrustedHTML
divElement.innerHTML = ADG_policyApi.convertPropertyToTrusted("div", "innerHTML", "<div></div>");
Matching SPA sites
This section only applies to AdGuard for Windows, AdGuard for Mac, AdGuard for Android, and AdGuard for Linux with CoreLibs v1.19 or later.
Many modern websites, such as YouTube, utilize Single Page Application (SPA) capabilities. Unlike traditional web applications, the page does not reload when navigating between pages. Instead, the content is updated dynamically using JavaScript, allowing for a smoother user experience.
On such websites, a userscript is invoked only once when the @match
or @include
directives are matched (unless @exclude
is matched). Due to the nature of SPAs, the userscript cannot be re-invoked on subsequent page changes because the global JavaScript context remains the same. To address this issue, userscripts can use the @grant window.onurlchange
directive.
// ==UserScript==
// @name SPA
// @namespace spa
// @version 1.0.0
// @match https://*/*
// @grant window.onurlchange
// @run-at document-start
// ==/UserScript==
// via window.onurlchange
window.onurlchange = (event) => {
console.log('URL changed to:', event.url);
};
// via window.addEventListener('urlchange')
window.addEventListener('urlchange', (event) => {
console.log('URL changed to:', event.url);
});
This will allow userscripts to listen for URL changes and handle them accordingly.
The urlchange
event is only triggered for full URL changes, such as a change in the path or query, but not for fragment (hash) changes.
Examples:
- Navigation from
https://example.com/page1
tohttps://example.com/page2
will trigger the event. - Navigation from
https://example.com/page1?query=1
tohttps://example.com/page1?query=2
will trigger the event. - Navigation from
https://example.com/page1#section1
tohttps://example.com/page1#section2
will NOT trigger the event.
The window.onurlchange
and window.addEventListener('urlchange', ...)
APIs are non-standard. To use them, you must explicitly grant them in your userscript with @grant window.onurlchange
.
If a website uses hash routing, userscripts can use the native DOM hashchange
event:
// ==UserScript==
// @name SPA
// @namespace spa
// @version 1.0.0
// @match https://*/*
// @run-at document-start
// ==/UserScript==
// via window.onhashchange
window.onhashchange = (event) => {
console.log(`Hash changed from "${event.oldURL}" to "${event.newURL}"`);
};
// via window.addEventListener('hashchange')
window.addEventListener('hashchange', (event) => {
console.log(`Hash changed from "${event.oldURL}" to "${event.newURL}"`);
});
Userstyles
Userstyles allow users to change the appearance of popular websites.
AdGuard has the option to upload or create your own userstyles. This is an advanced feature, so you will need some knowledge of HTML and CSS.
Currently, two AdGuard apps allow you to create and manage userstyles: AdGuard for Windows (v7.19 or later) and AdGuard for Mac (v2.16 or later). We also plan to implement this new feature in AdGuard for Android v4.8 in the nearest future.
This is an experimental feature, so if you encounter any problems while adding or creating a userstyle, please contact our support team at support@adguard.com.
How to set up a userstyle in AdGuard
You can download userstyles from various websites. One of the most popular userstyle websites is https://userstyles.world/, which we will use as an example for the following instructions on how to set up the userstyle in AdGuard.
Follow the link above and choose the userstyle you like
Click Copy next to the userstyle address
Open AdGuard settings → Extensions
Press the [+] button and paste the userstyle link
Pronto!
If you’re familiar with CSS rules, you can also create userstyles yourself.
We don’t support userstyles that contain @var
or @advanced
in the metadata. AdGuard also doesn’t support @preprocessor
without the default
value.
Open AdGuard settings → Extensions
Press the [+] button and choose the Create userstyle option. A new window will appear on your screen
To create a userstyle, first write the title with metadata, for example
/* ==UserStyle==
@name New userstyle
@version 1.0
==/UserStyle== */Write the CSS part after the meta data. AdGuard supports website domain names matching (
@-moz-document domain(…), …
). Por exemplo:body {
background: gray;
}Or:
@-moz-document domain('example.org'),
domain('example.net'),
domain('example.com') body {
background: gray;
}Once you’re finished, press Save and Close. Your new userstyle has been successfully added to AdGuard
Exemplo
/* ==UserStyle==
@name Example userstyle
@namespace https://example.org/userstyle
@homepageURL https://example.org/userstyle
@version 1.0.0
@license Other
@description This is an example
@author example
@preprocessor default
==/UserStyle== */
@-moz-document regexp("https?\:\/\/(www\.)?example\.(org|com).*") {
body {
background-color: #000000 !important;
}
}