> For the complete documentation index, see [llms.txt](https://docs.exoclick.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.exoclick.com/publishers/pt/adblock/adblock-dynamic-domains-api.md).

# Como trabalhar com a API de Domínios Dinâmicos do AdBlock

As ferramentas de AdBlock estão cada vez mais sofisticadas, o que representa desafios significativos para os publicadores que procuram maximizar a receita proveniente da publicidade online. Para ajudar a mitigar estes desafios, esta API permite que os publicadores ajustem dinamicamente os seus scripts com base em domínios ativos, reduzindo significativamente o risco de o conteúdo ser bloqueado por software AdBlock.

Ao garantir a entrega de anúncios por meio de domínios rotacionados regularmente, os publicadores podem:

* **Manter as fontes de receita:** Evitar interrupções causadas por anúncios bloqueados.
* **Melhorar a experiência do utilizador:** Entregar conteúdo publicitário de forma fluida, sem acionar a deteção do AdBlock.
* **Automatizar a gestão de domínios:** Eliminar atualizações manuais com um ciclo de vida automatizado de 7 dias para o domínio.

Novos domínios são gerados a cada 3 dias e ficam disponíveis através da API. Os domínios terão um ciclo de vida de 6 dias.

* 3 dias ativos
* 3 dias descontinuados

Assim que o ciclo de vida expirar, o domínio será desativado. Por motivos de desempenho, recomenda-se armazenar em cache o domínio durante 24 horas antes de solicitar um novo domínio da API.

Esta API está disponível apenas para **Script inline de Popunders** e **Vídeo In-Stream** zonas.

## Requisitos

Para usar esta API, os publicadores precisam de:

* Fazer uma **pedido GET** para o endpoint: <https://ads.exoclick.com/adblock-domains.php>
* Receberá um novo domínio de veiculação de anúncios na resposta
* De seguida, deve alterar o endpoint de sindicação usado na tag da sua zona de anúncios para o novo fornecido na resposta da API.

## Passos para Implementar

{% stepper %}
{% step %}

### Obter o Domínio Ativo

Para obter dinamicamente o Domínio ativo, **deve fazer uma chamada de API servidor a servidor**. Isto é crucial porque as chamadas à API podem ser bloqueadas se forem feitas do lado do cliente.

Aqui está um exemplo de chamada servidor a servidor em PHP:

```php
<?php
function fetchAdblockDomain()
{
    $endpoint = 'https://ads.exoclick.com/adblock-domains.php';
    $ch = curl_init($endpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        throw new Exception('Erro cURL: ' . curl_error($ch));
    }

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode === 200) {
        return $response;
    } else {
        throw new Exception("Erro HTTP: ({$httpCode}) Resposta: {$response}");
    }
}

try {
    echo fetchAdblockDomain();
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
```

E aqui está a resposta esperada da API:

```json
{
    "success": true,
    "message": "Domain found",
    "domain": "newsub.newdomain.com" 
}
```

{% endstep %}

{% step %}

### Atualize o seu script

Use o **domínio** retornado pelo endpoint para atualizar o domínio usado na sua zona de anúncios. O domínio original depende do formato do anúncio:

* Para **Vídeo In-Stream** zonas, altere a *tag VAST*:
  * **Antes** : `https://s.magsrv.com/v1/vast.php?t={random}&idzone={zoneId}`
  * **Depois** : `https://newsub.newdomain.com/v1/vast.php?t={random}&idzone={zoneId}`
* Para zonas Popunders, altere o *syndication\_host* no script inline:
  * **Antes** : `s.pemsrv.com`
  * **Depois** : `newsub.newdomain.com`
    {% endstep %}
    {% endstepper %}

## Detetar o AdBlock

Para detetar se o utilizador tem uma extensão de adblock ativada, você **deve alojar `ads.js` do lado do publicador** (o seu próprio domínio/CDN) e incluí-lo logo no início da sua `body` tag.

Não **não** solicitar `https://www.exoclick.com/ads.js` diretamente.

Crie o seu próprio `ads.js` ficheiro:

1. Crie um ficheiro chamado `ads.js` num caminho público no seu site (por exemplo `/js/ads.js`).
2. Adicione o seguinte conteúdo a esse ficheiro.
3. Carregue esse ficheiro a partir da sua página antes da lógica de integração de anúncios.

Conteúdo do ficheiro de referência:

```javascript
let bait_b3j4hu231 = true;
```

Depois, adicione a seguinte linha logo no início da sua `body` tag:

```html
<script src="/js/ads.js" type="text/javascript"></script>
```

Este script será bloqueado pelo AdBlock caso o cliente o esteja a usar, devido à presença das palavras-chave "exoclick" e "ads". Após carregar este script, um snippet JS tentará ler uma variável específica. Se a variável estiver indefinida ou inacessível, podemos determinar que o script foi bloqueado.

```html
<script src="/js/ads.js" type="text/javascript"></script>

<script>
    // Inicialize a variável insDomain com um valor predefinido
    let insDomain = 's.magsrv.com'; // Hospedeiro genérico para a rede
    let adb = ""; // Esta variável pode conter "&block=1", o que ajuda a acompanhar as estatísticas do Adblock

    // Obter domínios do Adblock usando um pedido GET para o ficheiro PHP
    async function fetchAdblockDomains() {
        try {
            // Efetue um pedido GET para fetchAdblockDomain.php (Passo 3.A).
            // Este é um pedido servidor a servidor para obter o domínio do Adblock.
            const response = await fetch('fetchAdblockDomain.php', {
                method: 'GET', // Especifique o método GET
            });

            // Verifique se a resposta foi bem-sucedida (estado 200)
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }

            // Analise a resposta como JSON
            const data = await response.json();
            console.log('Response data:', data); // Registe os dados da resposta para depuração

            // Chame a função para processar os domínios
            displayDomains(data);
        } catch (error) {
            // Registe quaisquer erros que ocorram durante a obtenção
            console.error('Error fetching domains:', error);
        }
    }
    // Processe e exiba os domínios, atualizando insDomain se success for true
    function displayDomains(domains) {
        console.log('Success status:', domains["success"]); // Registe o estado de sucesso
        console.log('Fetched domain:', domains["domain"]); // Registe o domínio obtido


        // Atualize a variável insDomain se a flag success for verdadeira
        if (domains["success"] && typeof bait_b3j4hu231 === 'undefined') {
            adb = '&block=1';
            insDomain = domains["domain"];
            console.log('Updated insDomain:', insDomain); // Registe o valor atualizado de insDomain
        }

        // Agora deve inicializar o Fluid Player usando a tag VAST:
        // const rdm = 't=' + Math.floor(Math.random() * 1000) + '&';
        // "https://" + insDomain + "/v1/vast.php?" + rdm + "idzone=ZONEID" + adb
    }

    // Chame automaticamente fetchAdblockDomains quando a página carregar
    window.onload = fetchAdblockDomains;
</script>
```

## Exemplos de Integração

Nestes dois exemplos estamos a usar `fetchAdblockDomain.php` como nome da chamada servidor a servidor para obter o domínio do Adblock.

### In-Stream

Para usar Domínios Dinâmicos com In-Stream, certifique-se de **incluir o player VAST dentro do script**caso contrário, o player carregará a zona de anúncios in-stream predefinida em vez de usar o domínio atualizado. Neste exemplo, estamos a usar o player HTML5 Fluidplayer.

```html
<script src="/js/ads.js" type="text/javascript"></script>

    <script>
        let insDomain = 's.magsrv.com'; // predefinido
        let adb = '';
        const ZONE_ID_PRE_ROLL = 'XXXXXXX';

        async function fetchAndApplyAdblockDomains() {
            try {
                const response = await fetch('fetchAdblockDomain.php');
                const data = await response.json();

                console.log('Response:', data);

                if (data.success && typeof bait_b3j4hu231 === 'undefined') {
                    // AdBlock detetado
                    adb = '&block=1';
                    insDomain = data.domain;
                    console.log('AdBlock detected: using API domain', insDomain);
                } else if (data.success) {
                    // Sem AdBlock
                    console.log('No AdBlock: using default domain');
                } else {
                    console.warn('Fallback: Using default domain due to error or no success');
                }
            } catch (err) {
                console.error('Error fetching domain:', err);
            }

            const rdm = 't=' + Math.floor(Math.random() * 1000) + '&';

            // Inicialize o FluidPlayer
            fluidPlayer('example-player', {
                layoutControls: {
                    primaryColor: "#28B8ED",
                    controlForwardBackward: {
                        show: true,
                        doubleTapMobile: false
                    },
                    timelinePreview: {
                        file: 'thumbnails.vtt',
                        type: 'VTT'
                    }
                },
                vastOptions: {
                    adList: [
                        {
                            roll: "preRoll",
                            vastTag: `https://${insDomain}/v1/vast.php?${rdm}idzone=${ZONE_ID_PRE_ROLL}${adb}`
                        }
                    ]
                }
            });
        }

        window.onload = fetchAndApplyAdblockDomains;

    </script>
```

### Popunder

```html
<script src="/js/ads.js" type="text/javascript"></script>
<!-- Ligação que aciona o popunder-->
<a href="#">Clique aqui</a> 
<script type="application/javascript">

    (async function () {
    let syndicationHost = 's.pemsrv.com';     
    try {
        const response = await fetch('fetchAdblockDomain.php', {
        method: 'GET', 
        })
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
            }
        const data = await response.json();
        console.log('Response data:', data);
        
        if (data.success && typeof bait_b3j4hu231 === 'undefined') {
            syndicationHost = data.domain;
        }
        else {
            console.log('No Adblock: using default domain.');
        }
    } catch (err) {
        console.error('Reverting to default domain due to error:', err);
    }

    // Zona de anúncios popunder
    function randStr(e,t){for(var n="",r=t||"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",o=0;o<e;o++)n+=r.charAt(Math.floor(Math.random()*r.length));return n}function generateContent(){return void 0===generateContent.val&&(generateContent.val="document.dispatchEvent("+randStr(4*Math.random()+3)+");"),generateContent.val}try{Object.defineProperty(document.currentScript,"innerHTML",{get:generateContent}),Object.defineProperty(document.currentScript,"textContent",{get:generateContent})}catch(e){};

    var adConfig = {
    "ads_host": "a.pemsrv.com",
    "syndication_host": syndicationHost,
    "idzone": 123456789,
    "popup_fallback": false,
    "popup_force": false,
    "chrome_enabled": true,
    "new_tab": false,
    "frequency_period": 5,
    "frequency_count": 1,
    "trigger_method": 3,
    "trigger_delay": 0,
    "capping_enabled": true,
    "tcf_enabled": true,
    "only_inline": false
};

window.document.querySelectorAll||(document.querySelectorAll=document.body.querySelectorAll=Object.querySelectorAll=function(e,o,t,i,n){var r=document,a=r.createStyleSheet();for(n=r.all,o=[],t=(e=e.replace(/\[for\b/gi,"[htmlFor").split(",")).length;t--;){for(a.addRule(e[t],"k:v"),i=n.length;i--;)n[i].currentStyle.k&&o.push(n[i]);a.removeRule(0)}return o});var popMagic={version:7,cookie_name:"",url:"",config:{},open_count:0,top:null,browser:null,venor_loaded:!1,venor:!1,tcfData:null,configTpl:{ads_host:"",syndication_host:"",idzone:"",frequency_period:720,frequency_count:1,trigger_method:1,trigger_class:"",popup_force:!1,popup_fallback:!1,chrome_enabled:!0,new_tab:!1,cat:"",tags:"",el:"",sub:"",sub2:"",sub3:"",only_inline:!1,trigger_delay:0,capping_enabled:!0,tcf_enabled:!1,cookieconsent:!0,should_fire:function(){return!0},on_redirect:null},init:function(e){if(void 0!==e.idzone&&e.idzone){void 0===e.customTargeting&&(e.customTargeting=[]),window.customTargeting=e.customTargeting||null;var o=Object.keys(e.customTargeting).filter(function(e){return e.search("ex_")>=0});for(var t in o.length&&o.forEach(function(e){return this.configTpl[e]=null}.bind(this)),this.configTpl)Object.prototype.hasOwnProperty.call(this.configTpl,t)&&(void 0!==e[t]?this.config[t]=e[t]:this.config[t]=this.configTpl[t]);if(void 0!==this.config.idzone&&""!==this.config.idzone){!0!==this.config.only_inline&&this.loadHosted();var i=this;this.checkTCFConsent(function(){"complete"===document.readyState?i.preparePopWait():i.addEventToElement(window,"load",i.preparePop)})}}},getCountFromCookie:function(){if(!this.config.cookieconsent)return 0;var e=popMagic.getCookie(popMagic.cookie_name),o=void 0===e?0:parseInt(e);return isNaN(o)&&(o=0),o},getLastOpenedTimeFromCookie:function(){var e=popMagic.getCookie(popMagic.cookie_name),o=null;if(void 0!==e){var t=e.split(";")[1];o=t>0?parseInt(t):0}return isNaN(o)&&(o=null),o},shouldShow:function(e){if(e=e||!1,!popMagic.config.capping_enabled){var o=!0,t=popMagic.config.should_fire;try{e||"function"!=typeof t||(o=Boolean(t()))}catch(e){console.error("Error executing should fire callback function:",e)}return o&&0===popMagic.open_count}if(popMagic.open_count>=popMagic.config.frequency_count)return!1;var i=popMagic.getCountFromCookie(),n=popMagic.getLastOpenedTimeFromCookie(),r=Math.floor(Date.now()/1e3),a=n+popMagic.config.trigger_delay;return!(n&&a>r)&&(popMagic.open_count=i,!(i>=popMagic.config.frequency_count))},venorShouldShow:function(){return popMagic.venor_loaded&&"0"===popMagic.venor},setAsOpened:function(e){var o=e?e.target||e.srcElement:null,t={id:"",tagName:"",classes:"",text:"",href:"",elm:""};void 0!==o&&null!=o&&(t={id:void 0!==o.id&&null!=o.id?o.id:"",tagName:void 0!==o.tagName&&null!=o.tagName?o.tagName:"",classes:void 0!==o.classList&&null!=o.classList?o.classList:"",text:void 0!==o.outerText&&null!=o.outerText?o.outerText:"",href:void 0!==o.href&&null!=o.href?o.href:"",elm:o});var i=new CustomEvent("creativeDisplayed-"+popMagic.config.idzone,{detail:t});if(document.dispatchEvent(i),popMagic.config.capping_enabled){var n=1;n=0!==popMagic.open_count?popMagic.open_count+1:popMagic.getCountFromCookie()+1;var r=Math.floor(Date.now()/1e3);popMagic.config.cookieconsent&&popMagic.setCookie(popMagic.cookie_name,n+";"+r,popMagic.config.frequency_period)}else++popMagic.open_count},loadHosted:function(){var e=document.createElement("script");for(var o in e.type="application/javascript",e.async=!0,e.src="//"+this.config.ads_host+"/popunder1000.js",e.id="popmagicldr",this.config)Object.prototype.hasOwnProperty.call(this.config,o)&&"ads_host"!==o&&"syndication_host"!==o&&e.setAttribute("data-exo-"+o,this.config[o]);var t=document.getElementsByTagName("body").item(0);t.firstChild?t.insertBefore(e,t.firstChild):t.appendChild(e)},preparePopWait:function(){setTimeout(popMagic.preparePop,400)},preparePop:function(){if("object"!=typeof exoJsPop101||!Object.prototype.hasOwnProperty.call(exoJsPop101,"add")){if(popMagic.top=self,popMagic.top!==self)try{top.document.location.toString()&&(popMagic.top=top)}catch(e){}if(popMagic.cookie_name="zone-cap-"+popMagic.config.idzone,popMagic.config.capping_enabled||(document.cookie=popMagic.cookie_name+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/"),popMagic.shouldShow(!0)){var e=new XMLHttpRequest;e.onreadystatechange=function(){e.readyState==XMLHttpRequest.DONE&&(popMagic.venor_loaded=!0,200==e.status?popMagic.venor=e.responseText:popMagic.venor="0")};var o="https:"!==document.location.protocol&&"http:"!==document.location.protocol?"https:":document.location.protocol;e.open("GET",o+"//"+popMagic.config.syndication_host+"/venor.php",!0);try{e.send()}catch(e){popMagic.venor_loaded=!0}}if(popMagic.buildUrl(),popMagic.browser=popMagic.browserDetector.getBrowserInfo(),popMagic.config.chrome_enabled||!popMagic.browser.isChrome){var t=popMagic.getPopMethod(popMagic.browser);popMagic.addEvent("click",t)}}},getPopMethod:function(e){return popMagic.config.popup_force||popMagic.config.popup_fallback&&e.isChrome&&e.version>=68&&!e.isMobile?popMagic.methods.popup:e.isMobile?popMagic.methods.default:e.isChrome?popMagic.methods.chromeTab:popMagic.methods.default},checkTCFConsent:function(e){if(this.config.tcf_enabled&&"function"==typeof window.__tcfapi){var o=this;window.__tcfapi("addEventListener",2,function(t,i){i&&(o.tcfData=t,"tcloaded"!==t.eventStatus&&"useractioncomplete"!==t.eventStatus||(window.__tcfapi("removeEventListener",2,function(){},t.listenerId),e()))})}else e()},buildUrl:function(){var e,o="https:"!==document.location.protocol&&"http:"!==document.location.protocol?"https:":document.location.protocol,t=top===self?document.URL:document.referrer,i={type:"inline",name:"popMagic",ver:this.version},n="";customTargeting&&Object.keys(customTargeting).length&&("object"==typeof customTargeting?Object.keys(customTargeting):customTargeting).forEach(function(o){"object"==typeof customTargeting?e=customTargeting[o]:Array.isArray(customTargeting)&&(e=scriptEl.getAttribute(o));var t=o.replace("data-exo-","");n+="&"+t+"="+e});var r=this.tcfData&&this.tcfData.gdprApplies&&!0===this.tcfData.gdprApplies?1:0;this.url=o+"//"+this.config.syndication_host+"/v1/link.php?cat="+this.config.cat+"&idzone="+this.config.idzone+"&type=8&p="+encodeURIComponent(t)+"&sub="+this.config.sub+(""!==this.config.sub2?"&sub2="+this.config.sub2:"")+(""!==this.config.sub3?"&sub3="+this.config.sub3:"")+"&block=1&el="+this.config.el+"&tags="+this.config.tags+"&scr_info="+function(e){var o=e.type+"|"+e.name+"|"+e.ver;return encodeURIComponent(btoa(o))}(i)+n+"&gdpr="+r+"&cb="+Math.floor(1e9*Math.random()),this.tcfData&&this.tcfData.tcString?this.url+="&gdpr_consent="+encodeURIComponent(this.tcfData.tcString):this.url+="&cookieconsent="+this.config.cookieconsent},addEventToElement:function(e,o,t){e.addEventListener?e.addEventListener(o,t,!1):e.attachEvent?(e["e"+o+t]=t,e[o+t]=function(){e["e"+o+t](window.event)},e.attachEvent("on"+o,e[o+t])):e["on"+o]=e["e"+o+t]},getTriggerClasses:function(){var e,o=[];-1===popMagic.config.trigger_class.indexOf(",")?e=popMagic.config.trigger_class.split(" "):e=popMagic.config.trigger_class.replace(/\s/g,"").split(",");for(var t=0;t<e.length;t++)""!==e[t]&&o.push("."+e[t]);return o},addEvent:function(e,o){var t;if("3"!=popMagic.config.trigger_method)if("2"!=popMagic.config.trigger_method||""==popMagic.config.trigger_class)if("4"!=popMagic.config.trigger_method||""==popMagic.config.trigger_class)if("5"!=popMagic.config.trigger_method||""==popMagic.config.trigger_class)popMagic.addEventToElement(document,e,o);else{var i="a"+popMagic.getTriggerClasses().map(function(e){return":not("+e+")"}).join("");t=document.querySelectorAll(i);for(var n=0;n<t.length;n++)popMagic.addEventToElement(t[n],e,o)}else{var r=popMagic.getTriggerClasses();popMagic.addEventToElement(document,e,function(e){r.some(function(o){return null!==e.target.closest(o)})||o.call(e.target,e)})}else{var a=popMagic.getTriggerClasses();for(t=document.querySelectorAll(a.join(", ")),n=0;n<t.length;n++)popMagic.addEventToElement(t[n],e,o)}else for(t=document.querySelectorAll("a"),n=0;n<t.length;n++)popMagic.addEventToElement(t[n],e,o)},setCookie:function(e,o,t){if(!this.config.cookieconsent)return!1;t=parseInt(t,10);var i=new Date;i.setMinutes(i.getMinutes()+parseInt(t));var n=encodeURIComponent(o)+"; expires="+i.toUTCString()+"; path=/";document.cookie=e+"="+n},getCookie:function(e){if(!this.config.cookieconsent)return!1;var o,t,i,n=document.cookie.split(";");for(o=0;o<n.length;o++)if(t=n[o].substr(0,n[o].indexOf("=")),i=n[o].substr(n[o].indexOf("=")+1),(t=t.replace(/^\s+|\s+$/g,"") )===e)return decodeURIComponent(i)},randStr:function(e,o){for(var t="",i=o||"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=0;n<e;n++)t+=i.charAt(Math.floor(Math.random()*i.length));return t},isValidUserEvent:function(e){return!(!("isTrusted"in e)||!e.isTrusted||"ie"===popMagic.browser.name||"safari"===popMagic.browser.name)||0!=e.screenX&&0!=e.screenY},isValidHref:function(e){if(void 0===e||""==e)return!1;return!/\s?javascript\s?:/i.test(e)},findLinkToOpen:function(e){var o=e,t=!1;try{for(var i=0;i<20&&!o.getAttribute("href")&&o!==document&&"html"!==o.nodeName.toLowerCase();)o=o.parentNode,i++;var n=o.getAttribute("target");n&&-1!==n.indexOf("_blank")||(t=o.getAttribute("href"))}catch(e){}return popMagic.isValidHref(t)||(t=!1),t||window.location.href},getPuId:function(){return"ok_"+Math.floor(89999999*Math.random()+1e7)},executeOnRedirect:function(){try{popMagic.config.capping_enabled||"function"!=typeof popMagic.config.on_redirect||popMagic.config.on_redirect()}catch(e){console.error("Error executing on redirect callback:",e)}},browserDetector:{browserDefinitions:[["firefox",/Firefox\/([0-9.]+)(?:\s|$)/],["opera",/Opera\/([0-9.]+)(?:\s|$)/],["opera",/OPR\/([0-9.]+)(:?\s|$)$/],["edge",/Edg(?:e|)\/([0-9._]+)/],["ie",/Trident\/7\.0.*rv:([0-9.]+)\).*Gecko$/],["ie",/MSIE\s([0-9.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["safari",/Version\/([0-9._]+).*Safari/],["chrome",/(?!Chrom.*Edg(?:e|))Chrom(?:e|ium)\/([0-9.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9.]+)(:?\s|$)/],["bb10",/BB10;\sTouch.*Version\/([0-9.]+)/],["android",/Android\s([0-9.]+)/],["ios",/Version\/([0-9._]+).*Mobile.*Safari.*/],["yandexbrowser",/YaBrowser\/([0-9._]+)/],["crios",/CriOS\/([0-9.]+)(:?\s|$)/]],isChromeOrChromium:function(){var e=window.navigator,o=(e.userAgent||"").toLowerCase(),t=e.vendor||"";if(-1!==o.indexOf("crios"))return!0;if(e.userAgentData&&Array.isArray(e.userAgentData.brands)&&e.userAgentData.brands.length>0){var i=e.userAgentData.brands,n=i.some(function(e){return"Google Chrome"===e.brand}),r=i.some(function(e){return"Chromium"===e.brand})&&2===i.length;return n||r}var a=!!window.chrome,c=-1!==o.indexOf("edg"),p=!!window.opr||-1!==o.indexOf("opr"),s=!(!e.brave||!e.brave.isBrave),g=-1!==o.indexOf("vivaldi"),l=-1!==o.indexOf("yabrowser"),d=-1!==o.indexOf("samsungbrowser"),u=-1!==o.indexOf("ucbrowser");return a&&"Google Inc."===t&&!c&&!p&&!s&&!g&&!l&&!d&&!u},getBrowserInfo:function(){var e=window.navigator.userAgent,o={name:"other",version:"1.0",versionNumber:1,isChrome:this.isChromeOrChromium(),isMobile:!!e.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile|WebOS|Windows Phone/i)};for(var t in this.browserDefinitions){var i=this.browserDefinitions[t];if(i[1].test(e)){var n=i[1].exec(e),r=n&&n[1].split(/[._]/).slice(0,3),a=Array.prototype.slice.call(r,1).join("")||"0";r&&r.length<3&&Array.prototype.push.apply(r,1===r.length?[0,0]:[0]),o.name=i[0],o.version=r.join("."),o.versionNumber=parseFloat(r[0]+"."+a);break}}return o}},methods:{default:function(e){if(!popMagic.shouldShow()||!popMagic.venorShouldShow()||!popMagic.isValidUserEvent(e))return!0;var o=e.target||e.srcElement,t=popMagic.findLinkToOpen(o);return window.open(t,"_blank"),popMagic.setAsOpened(e),popMagic.executeOnRedirect(),popMagic.top.document.location=popMagic.url,void 0!==e.preventDefault&&(e.preventDefault(),e.stopPropagation()),!0},chromeTab:function(e){if(!popMagic.shouldShow()||!popMagic.venorShouldShow()||!popMagic.isValidUserEvent(e))return!0;if(void 0===e.preventDefault)return!0;e.preventDefault(),e.stopPropagation();var o=top.window.document.createElement("a"),t=e.target||e.srcElement;o.href=popMagic.findLinkToOpen(t),document.getElementsByTagName("body")[0].appendChild(o);var i=new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window,screenX:0,screenY:0,clientX:0,clientY:0,ctrlKey:!0,altKey:!1,shiftKey:!1,metaKey:!0,button:0});i.preventDefault=void 0,o.dispatchEvent(i),o.parentNode.removeChild(o),popMagic.executeOnRedirect(),window.open(popMagic.url,"_self"),popMagic.setAsOpened(e)},popup:function(e){if(!popMagic.shouldShow()||!popMagic.venorShouldShow()||!popMagic.isValidUserEvent(e))return!0;var o="";if(popMagic.config.popup_fallback&&!popMagic.config.popup_force){var t=Math.max(Math.round(.8*window.innerHeight),300);o="menubar=1,resizable=1,width="+Math.max(Math.round(.7*window.innerWidth),300)+",height="+t+",top="+(window.screenY+100)+",left="+(window.screenX+100)}var i=document.location.href,n=window.open(i,popMagic.getPuId(),o);popMagic.setAsOpened(e),setTimeout(function(){n.location.href=popMagic.url,popMagic.executeOnRedirect()},200),void 0!==e.preventDefault&&(e.preventDefault(),e.stopPropagation())}}};    popMagic.init(adConfig);
})();
```

## Resolução de problemas

### Nenhum domínio devolvido

Por vezes, o endpoint pode devolver domínios vazios.

```json
{
    "success": false,
    "message": "Domain not found"
}
```

Registe sempre a resposta do endpoint durante a depuração para identificar potenciais problemas. Se success for `false`, contacte o suporte.

### O domínio predefinido é devolvido apesar de o Adblock estar ativado

Aqui estão algumas razões comuns pelas quais o seu script pode estar a usar o domínio predefinido apesar de o Adblock estar ativado:

* **ads.js não está alojado do lado do publicador**. Esta integração requer servir `ads.js` do seu próprio domínio (por exemplo `/js/ads.js`). Solicitar diretamente `https://www.exoclick.com/ads.js` não é suportado.
* **domínio predefinido sendo renderizado antes do domínio adblock**. Certifique-se de que o script que insere a zona de anúncios no seu site **aguarda sempre a chamada servidor-a-servidor**. Dependendo da cadeia de execução, o domínio predefinido pode ser adicionado ao site antes de o domínio adblock ser devolvido, o que impedirá o seu site de inserir o domínio atualizado.

Para obter mais assistência, contacte a equipa de apoio [aqui](https://www.exoclick.com/contact/).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.exoclick.com/publishers/pt/adblock/adblock-dynamic-domains-api.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
