Ir al contenido principal

Cómo trabajar con la API de dominios dinámicos de AdBlock

Las herramientas AdBlock son cada vez más sofisticadas, lo que plantea importantes retos a los editores que tratan de maximizar los ingresos procedentes de la publicidad en línea. Para ayudar a mitigar estos desafíos, esta API permite a los editores ajustar dinámicamente sus scripts en función de los dominios activos, lo que reduce significativamente el riesgo de que el contenido sea bloqueado por el software AdBlock.

Al garantizar la entrega de anuncios a través de dominios que rotan con regularidad, los editores pueden:

  • Mantenga los flujos de ingresos: Evite las interrupciones causadas por anuncios bloqueados.
  • Mejore la experiencia del usuario: Ofrezca contenido publicitario sin problemas y sin activar la detección de AdBlock.
  • Gestión de dominios automatizada: Elimine las actualizaciones manuales con un ciclo de vida de dominios automatizado de 7 días.

Los nuevos dominios se generan cada 3 días y están disponibles a través de la API. Los dominios tendrán un ciclo de vida de 6 días.

  • 3 días activo
  • 3 días obsoleto

Una vez que expire el ciclo de vida, el dominio se desactivará. Por motivos de rendimiento, se recomienda almacenar el dominio en caché durante 24 horas antes de solicitar un nuevo dominio a la API.

Esta API sólo está disponible para las zonas Popunders inline-script e In-Stream Video.

Requisitos

Para utilizar esta API, los editores deben :

  • Realice una solicitud GET al punto final: https://ads.exoclick.com/adblock-domains.php
  • Recibirá un nuevo dominio de ad-serving en la respuesta
  • A continuación, debe cambiar el punto final de sindicación utilizado en su etiqueta de zona publicitaria por el nuevo proporcionado en la respuesta de la API.

Pasos para la aplicación

Paso 1. Obtener el dominio activo

Para recuperar el dominio activo de forma dinámica, debe realizar una llamada API de servidor a servidor. Esto es crucial porque las llamadas a la API pueden bloquearse si se realizan desde el lado del cliente.

Petición de servidor a servidor (ejemplo PHP)

<?php
function fetchAdblockDomain()
{
$endpoint = 'https://ads.exoclick.com/adblock-domains.php'; // your ads domain

$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

$response = curl_exec($ch);

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

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

if ($httpCode == 200) {
return $response;
} else {
throw new Exception("HTTP Error: {$httpCode} - Response: {$response}");
}
}
try {
echo fetchAdblockDomain();
} catch (Exception $e) {
echo json_encode(['message' => $e->getMessage()]);
}
?>

Respuesta esperada de la API

{
"success": true,
"message": "Domain found",
"domain": "newsub.newdomain.com" // example
}

Paso 2. Actualice su guión

  • Obtener el script proporcionado en la etiqueta Zone HTML
  • Utilizar el dominio devuelto por el endpoint
  • Para las zonas In-Stream Video cambie la Etiqueta VAST:
  • Para zonas Popunders cambiar el syndication_host en el script inline:
    • Antes : s.pemsrv.com
    • After : newsub.nuevodominio.com

Detección de AdBlock

El siguiente fragmento de código le permite detectar si el cliente tiene activado AdBlock. Esto le permite seleccionar el dominio apropiado para la solicitud y añadir block=1 para mejorar las estadísticas de seguimiento de AdBlock. Vea el siguiente ejemplo:

// This script will be blocked by Adblock in case of the client is using it, due to the presence of the "exoclick" and "ads" keywords.
// After loading this script, a JS snipppet will attempt to read a specific variable.
// If the variable is undefined or inaccessible, we can determine that the script as been blocked.

<script src="https://www.exoclick.com/ads.js" type="text/javascript"></script>

<script>
// Initialize the insDomain variable with a default value
let insDomain = 's.magsrv.com'; // Generic host for the network
let adb = ""; // This variable may contain "&block=1" which helps track Adblock Statistics

// Fetch adblock domains using a GET request to the PHP file
async function fetchAdblockDomains() {
try {
// Perform a GET request to fetchAdblockDomain.php (Step 3.A).
// This is a server-to-server request to retreive the Adblock Domain.
const response = await fetch('fetchAdblockDomain.php', {
method: 'GET', // Specify the GET method
});

// Check if the response is successful (status 200)
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

// Parse the response as JSON
const data = await response.json();
console.log('Response data:', data); // Log the response data for debugging

// Call the function to process the domains
displayDomains(data);
} catch (error) {
// Log any errors that occur during the fetch
console.error('Error fetching domains:', error);
}
}
// Process and display the domains, updating insDomain if success is true
function displayDomains(domains) {
console.log('Success status:', domains["success"]); // Log the success status
console.log('Fetched domain:', domains["domain"]); // Log the fetched domain


// Update the insDomain variable if the success flag is true
if (domains["success"] && typeof bait_b3j4hu231 === 'undefined') {
adb = '&block=1';
insDomain = domains["domain"];
console.log('Updated insDomain:', insDomain); // Log the updated value of insDomain
}

// Now you should initialize Fluid Player using the vast tag:
// "https://" + insDomain + "v1/vast.php?idzone=ZONEID" + adb
}

// Automatically call fetchAdblockDomains when the page loads
window.onload = fetchAdblockDomains;
</script>

Ejemplo de integración

Paso 1 - Archivo PHP del lado del servidor (fetchAdblockDomain.php)

Cree un archivo llamado fetchAdblockDomain.php en su servidor:

<?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('Error cURL: ' . curl_error($ch));
}

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

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

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

Este script PHP obtiene un nuevo dominio para la entrega de anuncios.

Paso 2 - Lógica JavaScript para buscar y aplicar

En la sección <script>:

<script src="https://www.exoclick.com/ads.js" type="text/javascript"></script>

<script>
let insDomain = 's.magsrv.com'; // default
let adb = '';
let rdm = '';
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 detected
adb = '&block=1';
insDomain = data.domain;
console.log('AdBlock detected: using API domain', insDomain);
} else if (data.success) {
// No AdBlock
insDomain = 's.magsrv.com';
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);
// Fallback to default domain
}

// Initialize Fluid Player
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}`,
timer: 5
}
]
}
});
}

window.onload = fetchAndApplyAdblockDomains;

</script>

Solución de problemas

Problemas comunes

No se devuelve ningún dominio, por ejemplo:

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

Si el éxito es falso, póngase en contacto con el servicio de asistencia.

Registre siempre la respuesta del endpoint durante la depuración para identificar posibles problemas.

For further assistance, contact the support team here.