Esta referencia usa la notación de TypeScript para describir los tipos. En la siguiente tabla, se proporciona una breve explicación con ejemplos.
Expresión de tipo | |
---|---|
string |
Es el tipo de cadena primitiva. |
string[] |
Es un tipo de array, en el que los valores solo pueden ser cadenas. |
number | string |
Un tipo de unión, en el que el valor puede ser un número o una cadena. |
Array<number | string> |
Es un tipo de array, en el que los valores son de tipo complejo (unión). |
[number, string] |
Un tipo de tupla, en el que el valor es un array de dos elementos que debe contener un número y una cadena en ese orden. |
Slot |
Un tipo de objeto, en el que el valor es una instancia de googletag.Slot . |
() => void |
Es un tipo de función sin argumentos definidos ni valor de retorno. |
Para obtener más información sobre los tipos y las expresiones de tipo admitidos, consulta el Manual de TypeScript .
Anotaciones de tipos
Dos puntos después de una variable, un nombre de parámetro, un nombre de propiedad o una firma de función denotan una anotación de tipo. Las anotaciones de tipo describen los tipos que el elemento a la izquierda del colon puede aceptar o mostrar. En la siguiente tabla, se muestran ejemplos de anotaciones de tipo que puedes ver en esta referencia.
Anotaciones de tipo | |
---|---|
param: string |
Indica que param acepta o muestra un valor de cadena. Esta sintaxis se usa para variables, parámetros, propiedades y tipos de datos que se devuelven.
|
param?: number | string |
Indica que param es opcional, pero acepta un número o una cadena cuando se especifica. Esta sintaxis se usa para parámetros y propiedades.
|
...params: Array<() => void> |
Indica que params es un
parámetro de resto
que acepta funciones. Los parámetros Rest aceptan una cantidad ilimitada de valores del tipo especificado.
|
googletag
Espacios de nombres | |
---|---|
config | Interfaz de configuración principal para la configuración a nivel de la página. |
enums | Este es el espacio de nombres que usa GPT para los tipos de enum. |
events | Este es el espacio de nombres que usa GPT para los eventos. |
secure | Este es el espacio de nombres que usa GPT para administrar los indicadores seguros. |
Interfaces | |
---|---|
Command | El array de comandos acepta una secuencia de funciones y las invoca en orden. |
Companion | Servicio de anuncios complementarios |
Privacy | Objeto de configuración para la configuración de privacidad. |
Pub | Servicio de Anuncios para Editores |
Response | Es un objeto que representa una sola respuesta de anuncio. |
Rewarded | Es un objeto que representa la recompensa asociada con un anuncio recompensado. |
Safe | Es un objeto de configuración para contenedores de SafeFrame. |
Service | Es una clase de servicio base que contiene métodos comunes para todos los servicios. |
Size | Es un compilador para objetos de especificación de asignación de tamaño. |
Slot | El espacio es un objeto que representa un solo espacio publicitario en una página. |
Alias de tipo | |
---|---|
General | Es una configuración de tamaño válida para un espacio, que puede ser uno o varios tamaños. |
Multi | Es una lista de tamaños válidos individuales. |
Named | Son los tamaños designados que puede tener un espacio. |
Single | Un solo tamaño válido para un horario disponible. |
Single | Es un array de dos números que representan [ancho, alto]. |
Size | Es una asignación del tamaño del viewport a los tamaños de los anuncios. |
Size | Es una lista de asignaciones de tamaño. |
Variables | |
---|---|
api | Marca que indica que la API de GPT se cargó y está lista para que se le llame. |
cmd | Es una referencia a la cola de comandos global para la ejecución asíncrona de llamadas relacionadas con GPT. |
pubads | Marca que indica que PubAdsService está habilitado, cargado y en pleno funcionamiento. |
secure | Es una referencia al array de proveedores de indicadores seguros. |
Funciones | |
---|---|
companion | Muestra una referencia a CompanionAdsService. |
define | Construye un espacio publicitario fuera de página con la ruta de acceso de la unidad de anuncios proporcionada. |
define | Construye un espacio de anuncios con una ruta de unidad de anuncios y un tamaño determinados, y lo asocia con el ID de un elemento div en la página que contendrá el anuncio. |
destroy | Destruye los espacios determinados y quita todos los objetos y referencias relacionados de esos espacios de GPT. |
disable | Inhabilita la Consola para publicadores de Google. |
display | Le indica a los servicios de ranura que rendericen la ranura. |
enable | Habilita todos los servicios de GPT que se definieron para los espacios publicitarios de la página. |
get | Muestra la versión actual de GPT. |
open | Se abrirá la Consola para publicadores de Google. |
pubads | Muestra una referencia a PubAdsService. |
set | Establece el título de todos los iframes de contenedores de anuncios creados por PubAdsService a partir de este punto. |
set | Establece las opciones de configuración general de la página. |
size | Crea un nuevo SizeMappingBuilder. |
Alias de tipo
GeneralSize
GeneralSize: SingleSize | MultiSize
MultiSize
MultiSize: SingleSize[]
NamedSize
NamedSize: "fluid" | ["fluid"]
- flexible: El contenedor de anuncios ocupa el 100% del ancho del div superior y, luego, cambia el tamaño de su altura para adaptarse al contenido de la creatividad. Es similar al comportamiento de los elementos de bloque normales en una página. Se usa para los anuncios nativos (consulta el artículo relacionado). Ten en cuenta que tanto
fluid
como['fluid']
son formas aceptables para declarar un tamaño de espacio como fluido.
SingleSize
SingleSize: SingleSizeArray | NamedSize
SingleSizeArray
SingleSizeArray: [number, number]
SizeMapping
SizeMapping: [SingleSizeArray, GeneralSize]
SizeMappingArray
SizeMappingArray: SizeMapping[]
Variables
Const
apiReady
apiReady: boolean | undefined
undefined
hasta que la API esté lista.Ten en cuenta que la forma recomendada de controlar la operación asíncrona es usar googletag.cmd para poner en cola devoluciones de llamada para cuando GPT esté lista. Estas devoluciones de llamada no tienen que verificar googletag.apiReady, ya que se garantiza que se ejecutarán una vez que se configure la API.
Const
cmd
cmd: ((this: typeof globalThis) => void)[] | CommandArray
La sintaxis de la etiqueta GPT en la página inicializa la variable
googletag.cmd
en un array de JavaScript vacío, y cmd.push
es el método Array.push
estándar que agrega un elemento al final del array. Cuando se carga el código JavaScript de GPT, analiza el array y ejecuta todas las funciones en orden. Luego, la secuencia de comandos reemplaza cmd
por un objeto CommandArray cuyo método push se define para ejecutar el argumento de la función que se le pasa. Este mecanismo permite que GPT reduzca la latencia percibida recuperando el código JavaScript de forma asíncrona y, al mismo tiempo, permite que el navegador siga renderizando la página.- Ejemplo
JavaScript
googletag.cmd.push(() => { googletag.defineSlot("/1234567/sports", [160, 600]).addService(googletag.pubads()); });
JavaScript (heredado)
googletag.cmd.push(function () { googletag.defineSlot("/1234567/sports", [160, 600]).addService(googletag.pubads()); });
TypeScript
googletag.cmd.push(() => { googletag.defineSlot("/1234567/sports", [160, 600])!.addService(googletag.pubads()); });
Const
pubadsReady
pubadsReady: boolean | undefined
undefined
hasta que se llame a enableServices y se cargue e inicialice PubAdsService.secureSignalProviders
secureSignalProviders: SecureSignalProvider[] | SecureSignalProvidersArray | undefined
El array de proveedores de indicadores seguros acepta una secuencia de funciones generadoras de indicadores y las invoca en orden. Su objetivo es reemplazar un array estándar que se usa para poner en cola funciones generadoras de indicadores que se invocarán una vez que se cargue la GPT.
- Ejemplo
JavaScript
window.googletag = window.googletag || { cmd: [] }; googletag.secureSignalProviders = googletag.secureSignalProviders || []; googletag.secureSignalProviders.push({ id: "collector123", collectorFunction: () => { return Promise.resolve("signal"); }, });
JavaScript (heredado)
window.googletag = window.googletag || { cmd: [] }; googletag.secureSignalProviders = googletag.secureSignalProviders || []; googletag.secureSignalProviders.push({ id: "collector123", collectorFunction: function () { return Promise.resolve("signal"); }, });
TypeScript
window.googletag = window.googletag || { cmd: [] }; googletag.secureSignalProviders = googletag.secureSignalProviders || []; googletag.secureSignalProviders.push({ id: "collector123", collectorFunction: () => { return Promise.resolve("signal"); }, });
- Consulta también
Funciones
companionAds
companionAds(): CompanionAdsService
Muestra | |
---|---|
CompanionAdsService | El servicio de anuncios complementarios |
defineOutOfPageSlot
defineOutOfPageSlot(adUnitPath: string, div?: string | OutOfPageFormat): Slot | null
En el caso de los anuncios fuera de página personalizados,
div
es el ID del elemento div que contendrá el anuncio. Consulta el artículo sobre creatividades fuera de página para obtener más información.En el caso de los anuncios fuera de página administrados por GPT,
div
es un OutOfPageFormat compatible.- Ejemplo
JavaScript
// Define a custom out-of-page ad slot. googletag.defineOutOfPageSlot("/1234567/sports", "div-1"); // Define a GPT managed web interstitial ad slot. googletag.defineOutOfPageSlot("/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL);
JavaScript (heredado)
// Define a custom out-of-page ad slot. googletag.defineOutOfPageSlot("/1234567/sports", "div-1"); // Define a GPT managed web interstitial ad slot. googletag.defineOutOfPageSlot("/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL);
TypeScript
// Define a custom out-of-page ad slot. googletag.defineOutOfPageSlot("/1234567/sports", "div-1"); // Define a GPT managed web interstitial ad slot. googletag.defineOutOfPageSlot("/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL);
- Consulta también
Parámetros | |
---|---|
adUnitPath: string | Ruta de la unidad de anuncios completa con el código de red y el código de unidad de anuncios |
| Es el ID del div que contendrá esta unidad de anuncios o OutOfPageFormat. |
Muestra | |
---|---|
Slot | null | Es el espacio recién creado o null si no se puede crear uno. |
defineSlot
defineSlot(adUnitPath: string, size: GeneralSize, div?: string): Slot | null
- Ejemplo
JavaScript
googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
JavaScript (heredado)
googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
TypeScript
googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
- Consulta también
Parámetros | |
---|---|
adUnitPath: string | Ruta de la unidad de anuncios completa con el código de red y el código de unidad |
size: GeneralSize | Ancho y altura de la ranura agregada. Este es el tamaño que se usa en la solicitud de anuncio si no se proporciona una asignación de tamaño responsivo o si el tamaño del viewport es menor que el más pequeño proporcionado en la asignación. |
| Es el ID del div que contendrá esta unidad de anuncios. |
Muestra | |
---|---|
Slot | null | Es el espacio recién creado o null si no se puede crear uno. |
destroySlots
destroySlots(slots?: Slot[]): boolean
Si llamas a esta API en un espacio, se borrará el anuncio y se quitará el objeto del espacio del estado interno que mantiene GPT. Si llamas a más funciones en el objeto de inserción, se producirá un comportamiento indefinido. Ten en cuenta que es posible que el navegador no libere la memoria asociada con ese espacio si la página del publicador mantiene una referencia a él. Si llamas a esta API, el div asociado con ese espacio estará disponible para su reutilización.
En particular, destruir un espacio quita el anuncio de la vista de página de larga duración de GPT, de modo que las solicitudes futuras no se verán afectadas por obstáculos ni exclusiones competitivas que involucren a este anuncio. Si no llamas a esta función antes de quitar el div de un espacio de la página, se producirá un comportamiento indefinido.
- Ejemplo
JavaScript
// The calls to construct an ad and display contents. const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1"); googletag.display("div-1"); const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2"); googletag.display("div-2"); // This call to destroy only slot1. googletag.destroySlots([slot1]); // This call to destroy both slot1 and slot2. googletag.destroySlots([slot1, slot2]); // This call to destroy all slots. googletag.destroySlots();
JavaScript (heredado)
// The calls to construct an ad and display contents. var slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1"); googletag.display("div-1"); var slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2"); googletag.display("div-2"); // This call to destroy only slot1. googletag.destroySlots([slot1]); // This call to destroy both slot1 and slot2. googletag.destroySlots([slot1, slot2]); // This call to destroy all slots. googletag.destroySlots();
TypeScript
// The calls to construct an ad and display contents. const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!; googletag.display("div-1"); const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!; googletag.display("div-2"); // This call to destroy only slot1. googletag.destroySlots([slot1]); // This call to destroy both slot1 and slot2. googletag.destroySlots([slot1, slot2]); // This call to destroy all slots. googletag.destroySlots();
Parámetros | |
---|---|
| Es el array de ranuras que se destruirán. El array es opcional. Si no se especifica, se destruirán todos los espacios. |
Muestra | |
---|---|
boolean | true si se destruyeron los espacios, false de lo contrario. |
disablePublisherConsole
disablePublisherConsole(): void
- Consulta también
display
display(divOrSlot: string | Element | Slot): void
Si se usa la arquitectura de solicitud única (SRA), se recuperarán todos los espacios publicitarios que no se hayan recuperado en el momento en que se llame a este método. Para forzar que no se muestre un espacio publicitario, se debe quitar todo el div.
- Consulta también
Parámetros | |
---|---|
divOrSlot: string | Element | Slot | El ID del elemento div que contiene el espacio de anuncios, el elemento div o el objeto del espacio. Si se proporciona un elemento div, debe tener un atributo "id" que coincida con el ID que se pasa a defineSlot. |
enableServices
enableServices(): void
getVersion
getVersion(): string
- Consulta también
Muestra | |
---|---|
string | Es la cadena de versión de GPT que se está ejecutando. |
openConsole
openConsole(div?: string): void
- Ejemplo
JavaScript
// Calling with div ID. googletag.openConsole("div-1"); // Calling without div ID. googletag.openConsole();
JavaScript (heredado)
// Calling with div ID. googletag.openConsole("div-1"); // Calling without div ID. googletag.openConsole();
TypeScript
// Calling with div ID. googletag.openConsole("div-1"); // Calling without div ID. googletag.openConsole();
- Consulta también
Parámetros | |
---|---|
| Un ID de div del espacio publicitario. Este valor es opcional. Si se proporciona, la Consola para publicadores intentará abrirse con los detalles del espacio de anuncios especificado en la vista. |
pubads
pubads(): PubAdsService
Muestra | |
---|---|
PubAdsService | El servicio de Anuncios para publicadores |
setAdIframeTitle
setAdIframeTitle(title: string): void
- Ejemplo
JavaScript
googletag.setAdIframeTitle("title");
JavaScript (heredado)
googletag.setAdIframeTitle("title");
TypeScript
googletag.setAdIframeTitle("title");
Parámetros | |
---|---|
title: string | Es el nuevo título de todos los iframes del contenedor de anuncios. |
setConfig
setConfig(config: PageSettingsConfig): void
Parámetros | |
---|---|
config: PageSettingsConfig |
sizeMapping
sizeMapping(): SizeMappingBuilder
googletag.CommandArray
Métodos | |
---|---|
push | Ejecuta la secuencia de funciones especificadas en los argumentos en orden. |
Métodos
push
push(...f: ((this: typeof globalThis) => void)[]): number
- Ejemplo
JavaScript
googletag.cmd.push(() => { googletag.defineSlot("/1234567/sports", [160, 600]).addService(googletag.pubads()); });
JavaScript (heredado)
googletag.cmd.push(function () { googletag.defineSlot("/1234567/sports", [160, 600]).addService(googletag.pubads()); });
TypeScript
googletag.cmd.push(() => { googletag.defineSlot("/1234567/sports", [160, 600])!.addService(googletag.pubads()); });
Parámetros | |
---|---|
| Es una función de JavaScript que se ejecutará. La vinculación del tiempo de ejecución siempre será globalThis . Considera pasar una función de flecha para retener el valor this del contexto léxico circundante. |
Muestra | |
---|---|
number | Es la cantidad de comandos procesados hasta el momento. Esto es compatible con el valor que muestra Array.push (la longitud actual del array). |
googletag.CompanionAdsService
ExtiendeMétodos | |
---|---|
add | Registra un objeto de escucha que te permite configurar y llamar a una función de JavaScript cuando ocurre un evento de GPT específico en la página. Se heredó de |
get | Obtén la lista de los horarios asociados con este servicio. Se heredó de |
remove | Quita un objeto de escucha registrado anteriormente. Se heredó de |
set | Establece si los espacios publicitarios complementarios que no se completaron se reabastecerán automáticamente. |
- Consulta también
Métodos
setRefreshUnfilledSlots
setRefreshUnfilledSlots(value: boolean): void
Se puede llamar a este método varias veces durante el ciclo de vida de la página para activar y desactivar el reabastecimiento. Solo se reabastecerán los espacios que también estén registrados en PubAdsService. Debido a las restricciones de las políticas, este método no está diseñado para completar los espacios complementarios vacíos cuando se publica un video de Ad Exchange.
- Ejemplo
JavaScript
googletag.companionAds().setRefreshUnfilledSlots(true);
JavaScript (heredado)
googletag.companionAds().setRefreshUnfilledSlots(true);
TypeScript
googletag.companionAds().setRefreshUnfilledSlots(true);
Parámetros | |
---|---|
value: boolean | true para reabastecer automáticamente los espacios sin completar, false para dejarlos sin cambios. |
googletag.PrivacySettingsConfig
Propiedades | |
---|---|
child | Indica si la página debe tratarse como contenido dirigido a niños. |
limited | Habilita la publicación en el modo de anuncios limitados para ayudar a satisfacer las necesidades de cumplimiento normativo de los publicadores. |
non | Habilita la publicación en el modo de anuncios no personalizados para ayudar a satisfacer las necesidades de cumplimiento normativo de los publicadores. |
restrict | Permite que la publicación se ejecute en el modo de procesamiento restringido para ayudar a satisfacer las necesidades de cumplimiento reglamentario de los publicadores. |
traffic | Indica si las solicitudes representan tráfico orgánico o comprado. |
under | Indica si se deben marcar las solicitudes de anuncios como provenientes de usuarios que no alcanzan la edad de consentimiento. |
- Consulta también
Propiedades
Optional
childDirectedTreatment
childDirectedTreatment?: null | boolean
null
para borrar la configuración.Optional
limitedAds
limitedAds?: boolean
Puedes indicarle a GPT que solicite anuncios limitados de dos maneras:
- De forma automática, con un indicador de una plataforma de administración de consentimiento del MTC v2.0 de IAB
- De forma manual, configura el valor de este campo en
true
.
Ten en cuenta que no es necesario habilitar manualmente los anuncios limitados cuando se usa una CMP.
- Ejemplo
JavaScript
// Manually enable limited ads serving. // GPT must be loaded from the limited ads URL to configure this setting. googletag.pubads().setPrivacySettings({ limitedAds: true, });
JavaScript (heredado)
// Manually enable limited ads serving. // GPT must be loaded from the limited ads URL to configure this setting. googletag.pubads().setPrivacySettings({ limitedAds: true, });
TypeScript
// Manually enable limited ads serving. // GPT must be loaded from the limited ads URL to configure this setting. googletag.pubads().setPrivacySettings({ limitedAds: true, });
- Consulta también
Optional
nonPersonalizedAds
nonPersonalizedAds?: boolean
Optional
restrictDataProcessing
restrictDataProcessing?: boolean
Optional
trafficSource
trafficSource?: TrafficSource
undefined
en los informes.- Ejemplo
JavaScript
// Indicate requests represent organic traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.ORGANIC, }); // Indicate requests represent purchased traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.PURCHASED, });
JavaScript (heredado)
// Indicate requests represent organic traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.ORGANIC, }); // Indicate requests represent purchased traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.PURCHASED, });
TypeScript
// Indicate requests represent organic traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.ORGANIC, }); // Indicate requests represent purchased traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.PURCHASED, });
Optional
underAgeOfConsent
underAgeOfConsent?: null | boolean
null
para borrar la configuración.googletag.PubAdsService
ExtiendeMétodos | |
---|---|
add | Registra un objeto de escucha que te permite configurar y llamar a una función de JavaScript cuando ocurre un evento GPT específico en la página. Se heredó de |
clear | Quita los anuncios de los espacios determinados y los reemplaza por contenido en blanco. |
clear | Borra todas las etiquetas de exclusión de categorías de anuncios a nivel de la página. |
clear | Borra los parámetros de segmentación personalizada de una clave específica o de todas las claves. |
collapse | Habilita la contracción de los divs de los espacios publicitarios para que no ocupen espacio en la página cuando no haya contenido del anuncio para mostrar. |
disable | Inhabilita las solicitudes de anuncios en la carga de la página, pero permite que se soliciten anuncios con una llamada a PubAdsService.refresh. |
display | Construye y muestra un espacio de anuncios con la ruta de acceso y el tamaño de la unidad de anuncios proporcionados. |
enable | Habilita la carga diferida en GPT como lo define el objeto de configuración. |
enable | Habilita el modo de solicitud única para recuperar varios anuncios al mismo tiempo. |
enable | Indica a GPT que habrá anuncios de video en la página. |
get | Muestra el valor del atributo de AdSense asociado con la clave determinada. |
get | Muestra las claves de atributos que se establecieron en este servicio. |
get | Obtén la lista de los horarios asociados con este servicio. Se heredó de |
get | Devuelve un parámetro de segmentación a nivel del servicio personalizado específico que se configuró. |
get | Muestra la lista de todas las claves de segmentación personalizadas a nivel del servicio que se establecieron. |
is | Muestra si una llamada anterior a PubAdsService.disableInitialLoad inhabilitó correctamente las solicitudes iniciales de anuncios. |
refresh | Recupera y muestra anuncios nuevos para espacios específicos o todos los espacios de la página. |
remove | Quita un objeto de escucha registrado anteriormente. Se heredó de |
set | Establece valores para los atributos de AdSense que se aplican a todos los espacios publicitarios del servicio de anuncios para publicadores. |
set | Establece una exclusión de categoría de anuncios a nivel de la página para el nombre de etiqueta determinado. |
set | Habilita o inhabilita el centrado horizontal de los anuncios. |
set | Configura si todos los anuncios de la página se deben renderizar de forma forzosa con un contenedor de SafeFrame. |
set | Pasa información de ubicación de los sitios web para que puedas segmentar líneas de pedido por ubicación geográfica en ubicaciones específicas. |
set | Permite configurar todos los parámetros de configuración de privacidad desde una sola API con un objeto de configuración. |
set | Establece el valor del ID proporcionado por el publicador. |
set | Establece las preferencias a nivel de la página para la configuración de SafeFrame. |
set | Establece parámetros de segmentación personalizados para una clave determinada que se aplican a todos los espacios publicitarios del servicio de anuncios del publicador. |
set | Establece la información del contenido de video que se enviará junto con las solicitudes de anuncios para la segmentación y la exclusión de contenido. |
update | Cambia el correlator que se envía con las solicitudes de anuncios, lo que inicia una nueva vista de página. |
Métodos
clear
clear(slots?: Slot[]): boolean
En particular, borrar un espacio quita el anuncio de la vista de página de larga duración de la GPT, por lo que las solicitudes futuras no se verán afectadas por obstáculos ni exclusiones competitivas que involucren este anuncio.
- Ejemplo
JavaScript
const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1"); googletag.display("div-1"); const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2"); googletag.display("div-2"); // This call to clear only slot1. googletag.pubads().clear([slot1]); // This call to clear both slot1 and slot2. googletag.pubads().clear([slot1, slot2]); // This call to clear all slots. googletag.pubads().clear();
JavaScript (heredado)
var slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1"); googletag.display("div-1"); var slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2"); googletag.display("div-2"); // This call to clear only slot1. googletag.pubads().clear([slot1]); // This call to clear both slot1 and slot2. googletag.pubads().clear([slot1, slot2]); // This call to clear all slots. googletag.pubads().clear();
TypeScript
const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!; googletag.display("div-1"); const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!; googletag.display("div-2"); // This call to clear only slot1. googletag.pubads().clear([slot1]); // This call to clear both slot1 and slot2. googletag.pubads().clear([slot1, slot2]); // This call to clear all slots. googletag.pubads().clear();
Parámetros | |
---|---|
| Es el array de ranuras que se borrarán. El array es opcional. Si no se especifica, se borrarán todos los espacios. |
Muestra | |
---|---|
boolean | Muestra true si se borraron las ranuras, false en caso contrario. |
clearCategoryExclusions
clearCategoryExclusions(): PubAdsService
- Ejemplo
JavaScript
// Set category exclusion to exclude ads with 'AirlineAd' labels. googletag.pubads().setCategoryExclusion("AirlineAd"); // Make ad requests. No ad with 'AirlineAd' label will be returned. // Clear category exclusions so all ads can be returned. googletag.pubads().clearCategoryExclusions(); // Make ad requests. Any ad can be returned.
JavaScript (heredado)
// Set category exclusion to exclude ads with 'AirlineAd' labels. googletag.pubads().setCategoryExclusion("AirlineAd"); // Make ad requests. No ad with 'AirlineAd' label will be returned. // Clear category exclusions so all ads can be returned. googletag.pubads().clearCategoryExclusions(); // Make ad requests. Any ad can be returned.
TypeScript
// Set category exclusion to exclude ads with 'AirlineAd' labels. googletag.pubads().setCategoryExclusion("AirlineAd"); // Make ad requests. No ad with 'AirlineAd' label will be returned. // Clear category exclusions so all ads can be returned. googletag.pubads().clearCategoryExclusions(); // Make ad requests. Any ad can be returned.
- Consulta también
Muestra | |
---|---|
PubAdsService | El objeto de servicio al que se llamó al método. |
clearTargeting
clearTargeting(key?: string): PubAdsService
- Ejemplo
JavaScript
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().setTargeting("colors", "blue"); googletag.pubads().setTargeting("fruits", "apple"); googletag.pubads().clearTargeting("interests"); // Targeting 'colors' and 'fruits' are still present, while 'interests' // was cleared. googletag.pubads().clearTargeting(); // All targeting has been cleared.
JavaScript (heredado)
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().setTargeting("colors", "blue"); googletag.pubads().setTargeting("fruits", "apple"); googletag.pubads().clearTargeting("interests"); // Targeting 'colors' and 'fruits' are still present, while 'interests' // was cleared. googletag.pubads().clearTargeting(); // All targeting has been cleared.
TypeScript
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().setTargeting("colors", "blue"); googletag.pubads().setTargeting("fruits", "apple"); googletag.pubads().clearTargeting("interests"); // Targeting 'colors' and 'fruits' are still present, while 'interests' // was cleared. googletag.pubads().clearTargeting(); // All targeting has been cleared.
- Consulta también
Parámetros | |
---|---|
| Clave del parámetro de segmentación. La clave es opcional. Si no se especifica, se borrarán todos los parámetros de segmentación. |
Muestra | |
---|---|
PubAdsService | El objeto de servicio al que se llamó al método. |
collapseEmptyDivs
collapseEmptyDivs(collapseBeforeAdFetch?: boolean): boolean
Parámetros | |
---|---|
| Indica si se deben contraer los espacios incluso antes de que se recuperen los anuncios. Este parámetro es opcional. Si no se proporciona, se usará false como valor predeterminado. |
Muestra | |
---|---|
boolean | Devuelve true si se habilitó el modo de colapso de div y false si es imposible habilitar el modo de colapso porque se llamó al método después de habilitar el servicio. |
disableInitialLoad
disableInitialLoad(): void
refresh
.display
display(adUnitPath: string, size: GeneralSize, div?: string | Element, clickUrl?: string): void
Nota: Cuando se llama a este método, se crea una instantánea del estado del espacio y de la página para garantizar la coherencia cuando se envía la solicitud de anuncio y se renderiza la respuesta. Cualquier cambio que se realice en el estado del espacio o de la página después de que se llame a este método (incluida la segmentación, la configuración de privacidad, la aplicación forzosa de SafeFrame, etcétera) solo se aplicará a las solicitudes
display()
o refresh()
posteriores.- Ejemplo
JavaScript
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
JavaScript (heredado)
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
TypeScript
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
- Consulta también
Parámetros | |
---|---|
adUnitPath: string | Es la ruta de la unidad de anuncios del espacio que se renderizará. |
size: GeneralSize | Ancho y altura de la ranura. |
| El ID del div que contiene el espacio o el elemento div |
| Es la URL de clic que se usará en este espacio. |
enableLazyLoad
enableLazyLoad(config?: {
fetchMarginPercent?: number;
mobileScaling?: number;
renderMarginPercent?: number;
}): void
Nota: La recuperación diferida en SRA solo funciona si todos los espacios están fuera del margen de recuperación.
- Ejemplo
JavaScript
googletag.pubads().enableLazyLoad({ // Fetch slots within 5 viewports. fetchMarginPercent: 500, // Render slots within 2 viewports. renderMarginPercent: 200, // Double the above values on mobile. mobileScaling: 2.0, });
JavaScript (heredado)
googletag.pubads().enableLazyLoad({ // Fetch slots within 5 viewports. fetchMarginPercent: 500, // Render slots within 2 viewports. renderMarginPercent: 200, // Double the above values on mobile. mobileScaling: 2.0, });
TypeScript
googletag.pubads().enableLazyLoad({ // Fetch slots within 5 viewports. fetchMarginPercent: 500, // Render slots within 2 viewports. renderMarginPercent: 200, // Double the above values on mobile. mobileScaling: 2.0, });
- Consulta también
Parámetros | |
---|---|
| El objeto de configuración permite personalizar el comportamiento diferido. Cualquier configuración omitida usará un valor predeterminado establecido por Google que se ajustará con el tiempo. Para inhabilitar un parámetro de configuración en particular, como un margen de recuperación, establece el valor en -1 .
|
enableSingleRequest
enableSingleRequest(): boolean
- Consulta también
Muestra | |
---|---|
boolean | Devuelve true si se habilitó el modo de solicitud única y false si es imposible habilitarlo porque se llamó al método después de habilitar el servicio. |
enableVideoAds
enableVideoAds(): void
get
get(key: string): null | string
- Ejemplo
JavaScript
googletag.pubads().set("adsense_background_color", "#FFFFFF"); googletag.pubads().get("adsense_background_color"); // Returns '#FFFFFF'.
JavaScript (heredado)
googletag.pubads().set("adsense_background_color", "#FFFFFF"); googletag.pubads().get("adsense_background_color"); // Returns '#FFFFFF'.
TypeScript
googletag.pubads().set("adsense_background_color", "#FFFFFF"); googletag.pubads().get("adsense_background_color"); // Returns '#FFFFFF'.
- Consulta también
Parámetros | |
---|---|
key: string | Es el nombre del atributo que se debe buscar. |
Muestra | |
---|---|
null | string | Es el valor actual de la clave de atributo o null si la clave no está presente. |
getAttributeKeys
getAttributeKeys(): string[]
- Ejemplo
JavaScript
googletag.pubads().set("adsense_background_color", "#FFFFFF"); googletag.pubads().set("adsense_border_color", "#AABBCC"); googletag.pubads().getAttributeKeys(); // Returns ['adsense_background_color', 'adsense_border_color'].
JavaScript (heredado)
googletag.pubads().set("adsense_background_color", "#FFFFFF"); googletag.pubads().set("adsense_border_color", "#AABBCC"); googletag.pubads().getAttributeKeys(); // Returns ['adsense_background_color', 'adsense_border_color'].
TypeScript
googletag.pubads().set("adsense_background_color", "#FFFFFF"); googletag.pubads().set("adsense_border_color", "#AABBCC"); googletag.pubads().getAttributeKeys(); // Returns ['adsense_background_color', 'adsense_border_color'].
Muestra | |
---|---|
string[] | Es un array de claves de atributos establecidas en este servicio. El orden no está definido. |
getTargeting
getTargeting(key: string): string[]
- Ejemplo
JavaScript
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().getTargeting("interests"); // Returns ['sports']. googletag.pubads().getTargeting("age"); // Returns [] (empty array).
JavaScript (heredado)
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().getTargeting("interests"); // Returns ['sports']. googletag.pubads().getTargeting("age"); // Returns [] (empty array).
TypeScript
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().getTargeting("interests"); // Returns ['sports']. googletag.pubads().getTargeting("age"); // Returns [] (empty array).
Parámetros | |
---|---|
key: string | Es la clave de segmentación que se debe buscar. |
Muestra | |
---|---|
string[] | Los valores asociados con esta clave, o un array vacío si no hay tal clave. |
getTargetingKeys
getTargetingKeys(): string[]
- Ejemplo
JavaScript
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().setTargeting("colors", "blue"); googletag.pubads().getTargetingKeys(); // Returns ['interests', 'colors'].
JavaScript (heredado)
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().setTargeting("colors", "blue"); googletag.pubads().getTargetingKeys(); // Returns ['interests', 'colors'].
TypeScript
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().setTargeting("colors", "blue"); googletag.pubads().getTargetingKeys(); // Returns ['interests', 'colors'].
Muestra | |
---|---|
string[] | Es un array de claves de segmentación. El orden no está definido. |
isInitialLoadDisabled
isInitialLoadDisabled(): boolean
Muestra | |
---|---|
boolean | Muestra true si una llamada anterior a PubAdsService.disableInitialLoad se realizó correctamente; de lo contrario, muestra false . |
actualizar
refresh(slots?: null | Slot[], options?: {
changeCorrelator: boolean;
}): void
Para que el comportamiento sea adecuado en todos los navegadores, la llamada a
refresh
debe ir precedida de una llamada a display
el espacio de anuncios. Si se omite la llamada a display
, es posible que la actualización se comporte de forma inesperada. Si lo deseas, puedes usar el método PubAdsService.disableInitialLoad para evitar que display
recupere un anuncio.Si actualizas un espacio, se quitará el anuncio anterior de la vista de página de larga duración de GPT, de modo que las solicitudes futuras no se verán afectadas por obstáculos ni exclusiones competitivas que involucren ese anuncio.
- Ejemplo
JavaScript
const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1"); googletag.display("div-1"); const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2"); googletag.display("div-2"); // This call to refresh fetches a new ad for slot1 only. googletag.pubads().refresh([slot1]); // This call to refresh fetches a new ad for both slot1 and slot2. googletag.pubads().refresh([slot1, slot2]); // This call to refresh fetches a new ad for each slot. googletag.pubads().refresh(); // This call to refresh fetches a new ad for slot1, without changing // the correlator. googletag.pubads().refresh([slot1], { changeCorrelator: false }); // This call to refresh fetches a new ad for each slot, without // changing the correlator. googletag.pubads().refresh(null, { changeCorrelator: false });
JavaScript (heredado)
var slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1"); googletag.display("div-1"); var slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2"); googletag.display("div-2"); // This call to refresh fetches a new ad for slot1 only. googletag.pubads().refresh([slot1]); // This call to refresh fetches a new ad for both slot1 and slot2. googletag.pubads().refresh([slot1, slot2]); // This call to refresh fetches a new ad for each slot. googletag.pubads().refresh(); // This call to refresh fetches a new ad for slot1, without changing // the correlator. googletag.pubads().refresh([slot1], { changeCorrelator: false }); // This call to refresh fetches a new ad for each slot, without // changing the correlator. googletag.pubads().refresh(null, { changeCorrelator: false });
TypeScript
const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!; googletag.display("div-1"); const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!; googletag.display("div-2"); // This call to refresh fetches a new ad for slot1 only. googletag.pubads().refresh([slot1]); // This call to refresh fetches a new ad for both slot1 and slot2. googletag.pubads().refresh([slot1, slot2]); // This call to refresh fetches a new ad for each slot. googletag.pubads().refresh(); // This call to refresh fetches a new ad for slot1, without changing // the correlator. googletag.pubads().refresh([slot1], { changeCorrelator: false }); // This call to refresh fetches a new ad for each slot, without // changing the correlator. googletag.pubads().refresh(null, { changeCorrelator: false });
- Consulta también
Parámetros | |
---|---|
| Los espacios que se actualizarán. El array es opcional. Si no se especifica, se actualizarán todos los espacios. |
| Son las opciones de configuración asociadas con esta llamada de actualización.
|
set
set(key: string, value: string): PubAdsService
Si llamas a esta función más de una vez para la misma clave, se anularán los valores establecidos anteriormente para esa clave. Todos los valores deben establecerse antes de llamar a
display
o refresh
.- Ejemplo
JavaScript
googletag.pubads().set("adsense_background_color", "#FFFFFF");
JavaScript (heredado)
googletag.pubads().set("adsense_background_color", "#FFFFFF");
TypeScript
googletag.pubads().set("adsense_background_color", "#FFFFFF");
- Consulta también
Parámetros | |
---|---|
key: string | Es el nombre del atributo. |
value: string | Valor del atributo. |
Muestra | |
---|---|
PubAdsService | El objeto de servicio al que se llamó al método. |
setCategoryExclusion
setCategoryExclusion(categoryExclusion: string): PubAdsService
- Ejemplo
JavaScript
// Label = AirlineAd. googletag.pubads().setCategoryExclusion("AirlineAd");
JavaScript (heredado)
// Label = AirlineAd. googletag.pubads().setCategoryExclusion("AirlineAd");
TypeScript
// Label = AirlineAd. googletag.pubads().setCategoryExclusion("AirlineAd");
- Consulta también
Parámetros | |
---|---|
categoryExclusion: string | La etiqueta de exclusión de categoría de anuncios que deseas agregar. |
Muestra | |
---|---|
PubAdsService | El objeto de servicio al que se llamó al método. |
setCentering
setCentering(centerAds: boolean): void
Este método se debe invocar antes de llamar a
display
o refresh
, ya que solo se centrarán los anuncios que se soliciten después de llamar a este método.- Ejemplo
JavaScript
// Make ads centered. googletag.pubads().setCentering(true);
JavaScript (heredado)
// Make ads centered. googletag.pubads().setCentering(true);
TypeScript
// Make ads centered. googletag.pubads().setCentering(true);
Parámetros | |
---|---|
centerAds: boolean | true para centrar los anuncios, false para alinearlos a la izquierda. |
setForceSafeFrame
setForceSafeFrame(forceSafeFrame: boolean): PubAdsService
Ten en cuenta lo siguiente cuando uses esta API:
- Este parámetro de configuración solo tendrá efecto en las solicitudes de anuncios posteriores que se realicen para los respectivos espacios.
- Si se especifica, la configuración a nivel del espacio siempre anulará la configuración a nivel de la página.
- Si se establece en
true
(a nivel del espacio o de la página), el anuncio siempre se renderizará con un contenedor de SafeFrame, independientemente de la opción que se elija en la IU de Google Ad Manager. - Sin embargo, si se establece en
false
o no se especifica, el anuncio se renderizará con un contenedor de SafeFrame según el tipo de creatividad y la selección que se realice en la IU de Google Ad Manager. - Esta API se debe usar con precaución, ya que podría afectar el comportamiento de las creatividades que intentan salir de sus iframes o dependen de que se rendericen directamente en una página del publicador.
- Ejemplo
JavaScript
googletag.pubads().setForceSafeFrame(true); // The following slot will be opted-out of the page-level force // SafeFrame instruction. googletag .defineSlot("/1234567/sports", [160, 600], "div-1") .setForceSafeFrame(false) .addService(googletag.pubads()); // The following slot will have SafeFrame forced. googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads()); googletag.display("div-1"); googletag.display("div-2");
JavaScript (heredado)
googletag.pubads().setForceSafeFrame(true); // The following slot will be opted-out of the page-level force // SafeFrame instruction. googletag .defineSlot("/1234567/sports", [160, 600], "div-1") .setForceSafeFrame(false) .addService(googletag.pubads()); // The following slot will have SafeFrame forced. googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads()); googletag.display("div-1"); googletag.display("div-2");
TypeScript
googletag.pubads().setForceSafeFrame(true); // The following slot will be opted-out of the page-level force // SafeFrame instruction. googletag .defineSlot("/1234567/sports", [160, 600], "div-1")! .setForceSafeFrame(false) .addService(googletag.pubads()); // The following slot will have SafeFrame forced. googletag.defineSlot("/1234567/news", [160, 600], "div-2")!.addService(googletag.pubads()); googletag.display("div-1"); googletag.display("div-2");
- Consulta también
Parámetros | |
---|---|
forceSafeFrame: boolean | true para forzar que todos los anuncios de la página se rendericen en SafeFrames y false para cambiar el parámetro de configuración anterior a "false". Si no se especifica antes, establecerlo en false no cambiará nada. |
Muestra | |
---|---|
PubAdsService | El objeto de servicio al que se llamó a la función. |
setLocation
setLocation(address: string): PubAdsService
- Ejemplo
JavaScript
// Postal code: googletag.pubads().setLocation("10001,US");
JavaScript (heredado)
// Postal code: googletag.pubads().setLocation("10001,US");
TypeScript
// Postal code: googletag.pubads().setLocation("10001,US");
Parámetros | |
---|---|
address: string | Dirección en formato libre. |
Muestra | |
---|---|
PubAdsService | El objeto de servicio al que se llamó al método. |
setPrivacySettings
setPrivacySettings(privacySettings: PrivacySettingsConfig): PubAdsService
- Ejemplo
JavaScript
googletag.pubads().setPrivacySettings({ restrictDataProcessing: true, }); // Set multiple privacy settings at the same time. googletag.pubads().setPrivacySettings({ childDirectedTreatment: true, underAgeOfConsent: true, }); // Clear the configuration for childDirectedTreatment. googletag.pubads().setPrivacySettings({ childDirectedTreatment: null, });
JavaScript (heredado)
googletag.pubads().setPrivacySettings({ restrictDataProcessing: true, }); // Set multiple privacy settings at the same time. googletag.pubads().setPrivacySettings({ childDirectedTreatment: true, underAgeOfConsent: true, }); // Clear the configuration for childDirectedTreatment. googletag.pubads().setPrivacySettings({ childDirectedTreatment: null, });
TypeScript
googletag.pubads().setPrivacySettings({ restrictDataProcessing: true, }); // Set multiple privacy settings at the same time. googletag.pubads().setPrivacySettings({ childDirectedTreatment: true, underAgeOfConsent: true, }); // Clear the configuration for childDirectedTreatment. googletag.pubads().setPrivacySettings({ childDirectedTreatment: null, });
Parámetros | |
---|---|
privacySettings: PrivacySettingsConfig | Objeto que contiene la configuración de la configuración de privacidad. |
Muestra | |
---|---|
PubAdsService | El objeto de servicio al que se llamó a la función. |
setPublisherProvidedId
setPublisherProvidedId(ppid: string): PubAdsService
- Ejemplo
JavaScript
googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
JavaScript (heredado)
googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
TypeScript
googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
- Consulta también
Parámetros | |
---|---|
ppid: string | Es un ID alfanumérico que proporciona el publicador. Debe tener entre 32 y 150 caracteres. |
Muestra | |
---|---|
PubAdsService | El objeto de servicio al que se llamó al método. |
setSafeFrameConfig
setSafeFrameConfig(config: SafeFrameConfig): PubAdsService
Si se especifican, las preferencias a nivel del espacio anularán estas preferencias a nivel de la página.
- Ejemplo
JavaScript
googletag.pubads().setForceSafeFrame(true); const pageConfig = { allowOverlayExpansion: true, allowPushExpansion: true, sandbox: true, }; const slotConfig = { allowOverlayExpansion: false }; googletag.pubads().setSafeFrameConfig(pageConfig); // The following slot will not allow for expansion by overlay. googletag .defineSlot("/1234567/sports", [160, 600], "div-1") .setSafeFrameConfig(slotConfig) .addService(googletag.pubads()); // The following slot will inherit the page level settings, and hence // would allow for expansion by overlay. googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads()); googletag.display("div-1"); googletag.display("div-2");
JavaScript (heredado)
googletag.pubads().setForceSafeFrame(true); var pageConfig = { allowOverlayExpansion: true, allowPushExpansion: true, sandbox: true, }; var slotConfig = { allowOverlayExpansion: false }; googletag.pubads().setSafeFrameConfig(pageConfig); // The following slot will not allow for expansion by overlay. googletag .defineSlot("/1234567/sports", [160, 600], "div-1") .setSafeFrameConfig(slotConfig) .addService(googletag.pubads()); // The following slot will inherit the page level settings, and hence // would allow for expansion by overlay. googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads()); googletag.display("div-1"); googletag.display("div-2");
TypeScript
googletag.pubads().setForceSafeFrame(true); const pageConfig = { allowOverlayExpansion: true, allowPushExpansion: true, sandbox: true, }; const slotConfig = { allowOverlayExpansion: false }; googletag.pubads().setSafeFrameConfig(pageConfig); // The following slot will not allow for expansion by overlay. googletag .defineSlot("/1234567/sports", [160, 600], "div-1")! .setSafeFrameConfig(slotConfig) .addService(googletag.pubads()); // The following slot will inherit the page level settings, and hence // would allow for expansion by overlay. googletag.defineSlot("/1234567/news", [160, 600], "div-2")!.addService(googletag.pubads()); googletag.display("div-1"); googletag.display("div-2");
- Consulta también
Parámetros | |
---|---|
config: SafeFrameConfig | El objeto de configuración |
Muestra | |
---|---|
PubAdsService | El objeto de servicio al que se llamó al método. |
setTargeting
setTargeting(key: string, value: string | string[]): PubAdsService
- Ejemplo
JavaScript
// Example with a single value for a key. googletag.pubads().setTargeting("interests", "sports"); // Example with multiple values for a key inside in an array. googletag.pubads().setTargeting("interests", ["sports", "music"]);
JavaScript (heredado)
// Example with a single value for a key. googletag.pubads().setTargeting("interests", "sports"); // Example with multiple values for a key inside in an array. googletag.pubads().setTargeting("interests", ["sports", "music"]);
TypeScript
// Example with a single value for a key. googletag.pubads().setTargeting("interests", "sports"); // Example with multiple values for a key inside in an array. googletag.pubads().setTargeting("interests", ["sports", "music"]);
- Consulta también
Parámetros | |
---|---|
key: string | Clave del parámetro de segmentación. |
value: string | string[] | Valor o array de valores del parámetro de segmentación |
Muestra | |
---|---|
PubAdsService | El objeto de servicio al que se llamó al método. |
setVideoContent
setVideoContent(videoContentId: string, videoCmsId: string): void
videoContentId
y videoCmsId
, usa los valores que se proporcionan al servicio de transferencia de contenido de Google Ad Manager.- Consulta también
Parámetros | |
---|---|
videoContentId: string | El ID de contenido del video |
videoCmsId: string | El ID del CMS del video |
updateCorrelator
updateCorrelator(): PubAdsService
Nota: Esto no tiene efecto en la vista de página de larga duración de GPT, que refleja automáticamente los anuncios que realmente se encuentran en la página y no tiene fecha de vencimiento.
- Ejemplo
JavaScript
// Assume that the correlator is currently 12345. All ad requests made // by this page will currently use that value. // Replace the current correlator with a new correlator. googletag.pubads().updateCorrelator(); // The correlator will now be a new randomly selected value, different // from 12345. All subsequent ad requests made by this page will use // the new value.
JavaScript (heredado)
// Assume that the correlator is currently 12345. All ad requests made // by this page will currently use that value. // Replace the current correlator with a new correlator. googletag.pubads().updateCorrelator(); // The correlator will now be a new randomly selected value, different // from 12345. All subsequent ad requests made by this page will use // the new value.
TypeScript
// Assume that the correlator is currently 12345. All ad requests made // by this page will currently use that value. // Replace the current correlator with a new correlator. googletag.pubads().updateCorrelator(); // The correlator will now be a new randomly selected value, different // from 12345. All subsequent ad requests made by this page will use // the new value.
Muestra | |
---|---|
PubAdsService | El objeto de servicio al que se llamó a la función. |
googletag.ResponseInformation
Propiedades | |
---|---|
advertiser | Es el ID del anunciante. |
campaign | El ID de la campaña. |
creative | Es el ID de la creatividad. |
creative | Es el ID de la plantilla del anuncio. |
line | Es el ID de la línea de pedido. |
- Consulta también
Propiedades
advertiserId
advertiserId: null | number
campaignId
campaignId: null | number
creativeId
creativeId: null | number
creativeTemplateId
creativeTemplateId: null | number
lineItemId
lineItemId: null | number
googletag.RewardedPayload
Propiedades | |
---|---|
amount | Es la cantidad de artículos incluidos en la recompensa. |
type | Es el tipo de elemento incluido en la recompensa (por ejemplo, "coin"). |
- Consulta también
Propiedades
amount
amount: number
type
type: string
googletag.SafeFrameConfig
Propiedades | |
---|---|
allow | Indica si SafeFrame debe permitir que el contenido del anuncio se expanda superponiendo el contenido de la página. |
allow | Indica si SafeFrame debe permitir que el contenido del anuncio se expanda mediante el envío de contenido de la página. |
sandbox | Indica si SafeFrame debe usar el atributo de zona de pruebas de HTML5 para evitar la navegación de nivel superior sin interacción del usuario. |
use | Obsoleto. Determina si SafeFrame debe usar subdominios aleatorios para las creatividades de reservación. |
- Consulta también
Propiedades
Optional
allowOverlayExpansion
allowOverlayExpansion?: boolean
Optional
allowPushExpansion
allowPushExpansion?: boolean
Optional
sandbox
sandbox?: boolean
true
(no se puede forzar a false
). Ten en cuenta que el atributo de zona de pruebas inhabilita los complementos (p.ej., Flash).Optional
useUniqueDomain
useUniqueDomain?: null | boolean
null
para borrar el valor almacenado.Nota: Esta función está habilitada de forma predeterminada.
- Consulta también
googletag.Service
Métodos | |
---|---|
add | Registra un objeto de escucha que te permite configurar y llamar a una función de JavaScript cuando ocurre un evento GPT específico en la página. |
get | Obtén la lista de los horarios asociados con este servicio. |
remove | Quita un objeto de escucha registrado anteriormente. |
Métodos
addEventListener
addEventListener<K extends keyof EventTypeMap>(eventType: K, listener: ((arg: EventTypeMap[K]) => void)): Service
- events.GameManualInterstitialSlotClosedEvent
- events.GameManualInterstitialSlotReadyEvent
- events.ImpressionViewableEvent
- events.RewardedSlotClosedEvent
- events.RewardedSlotGrantedEvent
- events.RewardedSlotReadyEvent
- events.SlotOnloadEvent
- events.SlotRenderEndedEvent
- events.SlotRequestedEvent
- events.SlotResponseReceived
- events.SlotVisibilityChangedEvent
- Ejemplo
JavaScript
// 1. Adding an event listener for the PubAdsService. googletag.pubads().addEventListener("slotOnload", (event) => { console.log("Slot has been loaded:"); console.log(event); }); // 2. Adding an event listener with slot specific logic. // Listeners operate at service level, which means that you cannot add // a listener for an event for a specific slot only. You can, however, // programmatically filter a listener to respond only to a certain ad // slot, using this pattern: const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", (event) => { if (event.slot === targetSlot) { // Slot specific logic. } });
JavaScript (heredado)
// 1. Adding an event listener for the PubAdsService. googletag.pubads().addEventListener("slotOnload", function (event) { console.log("Slot has been loaded:"); console.log(event); }); // 2. Adding an event listener with slot specific logic. // Listeners operate at service level, which means that you cannot add // a listener for an event for a specific slot only. You can, however, // programmatically filter a listener to respond only to a certain ad // slot, using this pattern: var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", function (event) { if (event.slot === targetSlot) { // Slot specific logic. } });
TypeScript
// 1. Adding an event listener for the PubAdsService. googletag.pubads().addEventListener("slotOnload", (event) => { console.log("Slot has been loaded:"); console.log(event); }); // 2. Adding an event listener with slot specific logic. // Listeners operate at service level, which means that you cannot add // a listener for an event for a specific slot only. You can, however, // programmatically filter a listener to respond only to a certain ad // slot, using this pattern: const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", (event) => { if (event.slot === targetSlot) { // Slot specific logic. } });
- Consulta también
Parámetros | |
---|---|
eventType: K | Es una cadena que representa el tipo de evento que genera GPT. Los tipos de eventos distinguen mayúsculas de minúsculas. |
listener: ((arg: EventTypeMap[K]) => void) | Es una función que toma un solo argumento de objeto de evento. |
Muestra | |
---|---|
Service | El objeto de servicio al que se llamó al método. |
getSlots
removeEventListener
removeEventListener<K extends keyof EventTypeMap>(eventType: K, listener: ((event: EventTypeMap[K]) => void)): void
- Ejemplo
JavaScript
googletag.cmd.push(() => { // Define a new ad slot. googletag.defineSlot("/6355419/Travel", [728, 90], "div-for-slot").addService(googletag.pubads()); // Define a new function that removes itself via removeEventListener // after the impressionViewable event fires. const onViewableListener = (event) => { googletag.pubads().removeEventListener("impressionViewable", onViewableListener); setTimeout(() => { googletag.pubads().refresh([event.slot]); }, 30000); }; // Add onViewableListener as a listener for impressionViewable events. googletag.pubads().addEventListener("impressionViewable", onViewableListener); googletag.enableServices(); });
JavaScript (heredado)
googletag.cmd.push(function () { // Define a new ad slot. googletag.defineSlot("/6355419/Travel", [728, 90], "div-for-slot").addService(googletag.pubads()); // Define a new function that removes itself via removeEventListener // after the impressionViewable event fires. var onViewableListener = function (event) { googletag.pubads().removeEventListener("impressionViewable", onViewableListener); setTimeout(function () { googletag.pubads().refresh([event.slot]); }, 30000); }; // Add onViewableListener as a listener for impressionViewable events. googletag.pubads().addEventListener("impressionViewable", onViewableListener); googletag.enableServices(); });
TypeScript
googletag.cmd.push(() => { // Define a new ad slot. googletag .defineSlot("/6355419/Travel", [728, 90], "div-for-slot")! .addService(googletag.pubads()); // Define a new function that removes itself via removeEventListener // after the impressionViewable event fires. const onViewableListener = (event: googletag.events.ImpressionViewableEvent) => { googletag.pubads().removeEventListener("impressionViewable", onViewableListener); setTimeout(() => { googletag.pubads().refresh([event.slot]); }, 30000); }; // Add onViewableListener as a listener for impressionViewable events. googletag.pubads().addEventListener("impressionViewable", onViewableListener); googletag.enableServices(); });
Parámetros | |
---|---|
eventType: K | Es una cadena que representa el tipo de evento que genera GPT. Los tipos de eventos distinguen mayúsculas de minúsculas. |
listener: ((event: EventTypeMap[K]) => void) | Es una función que toma un solo argumento de objeto de evento. |
googletag.SizeMappingBuilder
Métodos | |
---|---|
add | Agrega una asignación de un array de un solo tamaño (que representa el viewport) a un array de un solo tamaño o de varios tamaños que representa el espacio. |
build | Compila una especificación de mapa de tamaño a partir de las asignaciones que se agregaron a este compilador. |
- Consulta también
Métodos
addSize
addSize(viewportSize: SingleSizeArray, slotSize: GeneralSize): SizeMappingBuilder
- Ejemplo
JavaScript
// Mapping 1 googletag .sizeMapping() .addSize([1024, 768], [970, 250]) .addSize([980, 690], [728, 90]) .addSize([640, 480], "fluid") .addSize([0, 0], [88, 31]) // All viewports < 640x480 .build(); // Mapping 2 googletag .sizeMapping() .addSize([1024, 768], [970, 250]) .addSize([980, 690], []) .addSize([640, 480], [120, 60]) .addSize([0, 0], []) .build(); // Mapping 2 will not show any ads for the following viewport sizes: // [1024, 768] > size >= [980, 690] and // [640, 480] > size >= [0, 0]
JavaScript (heredado)
// Mapping 1 googletag .sizeMapping() .addSize([1024, 768], [970, 250]) .addSize([980, 690], [728, 90]) .addSize([640, 480], "fluid") .addSize([0, 0], [88, 31]) // All viewports < 640x480 .build(); // Mapping 2 googletag .sizeMapping() .addSize([1024, 768], [970, 250]) .addSize([980, 690], []) .addSize([640, 480], [120, 60]) .addSize([0, 0], []) .build(); // Mapping 2 will not show any ads for the following viewport sizes: // [1024, 768] > size >= [980, 690] and // [640, 480] > size >= [0, 0]
TypeScript
// Mapping 1 googletag .sizeMapping() .addSize([1024, 768], [970, 250]) .addSize([980, 690], [728, 90]) .addSize([640, 480], "fluid") .addSize([0, 0], [88, 31]) // All viewports < 640x480 .build(); // Mapping 2 googletag .sizeMapping() .addSize([1024, 768], [970, 250]) .addSize([980, 690], []) .addSize([640, 480], [120, 60]) .addSize([0, 0], []) .build(); // Mapping 2 will not show any ads for the following viewport sizes: // [1024, 768] > size >= [980, 690] and // [640, 480] > size >= [0, 0]
Parámetros | |
---|---|
viewportSize: SingleSizeArray | Es el tamaño del viewport para esta entrada de asignación. |
slotSize: GeneralSize | Los tamaños del espacio para esta entrada de asignación. |
Muestra | |
---|---|
SizeMappingBuilder | Es una referencia a este compilador. |
build
build(): null | SizeMappingArray
Si se proporcionaron asignaciones no válidas, este método mostrará
null
. De lo contrario, muestra una especificación en el formato correcto para pasar a Slot.defineSizeMapping.Nota: El comportamiento del compilador después de llamar a este método no está definido.
Muestra | |
---|---|
null | SizeMappingArray | El resultado que compiló este compilador. Puede ser nulo si se proporcionaron asignaciones de tamaño no válidas. |
googletag.Slot
Métodos | |
---|---|
add | Agrega un servicio a este espacio. |
clear | Borra todas las etiquetas de exclusión de categorías de anuncios a nivel del espacio para este espacio. |
clear | Borra parámetros de segmentación personalizados específicos o todos los parámetros de segmentación a nivel del espacio publicitario para este espacio. |
define | Establece un array de asignaciones de un tamaño mínimo de viewport al tamaño del slot para este slot. |
get | Muestra el valor del atributo de AdSense asociado con la clave determinada para este espacio. |
get | Muestra la ruta de acceso completa de la unidad de anuncios, con el código de red y la ruta de acceso de la unidad de anuncios. |
get | Muestra la lista de claves de atributos establecidas en este espacio. |
get | Devuelve las etiquetas de exclusión de categorías de anuncios para este espacio. |
get | Muestra la información de la respuesta del anuncio. |
get | Muestra el ID del div de la ranura proporcionado cuando se definió la ranura. |
get | Devuelve un parámetro de segmentación personalizada específico establecido en este espacio. |
get | Muestra la lista de todas las claves de segmentación personalizadas configuradas en este espacio. |
set | Establece un valor para un atributo de AdSense en este espacio publicitario. |
set | Establece una etiqueta de exclusión de categoría de anuncio a nivel del espacio en este espacio. |
set | Establece la URL de clic a la que se redireccionará a los usuarios después de que hagan clic en el anuncio. |
set | Establece si se debe ocultar el espacio div cuando no hay un anuncio en él. |
set | Establece las opciones de configuración generales para este espacio. |
set | Configura si los anuncios de este espacio publicitario deben renderizarse de forma forzosa con un contenedor de SafeFrame. |
set | Establece las preferencias a nivel del espacio para la configuración de SafeFrame. |
set | Establece un parámetro de segmentación personalizado para este espacio. |
update | Establece parámetros de segmentación personalizados para este espacio, a partir de un mapa clave-valor en un objeto JSON. |
Métodos
addService
addService(service: Service): Slot
- Ejemplo
JavaScript
googletag.defineSlot("/1234567/sports", [160, 600], "div").addService(googletag.pubads());
JavaScript (heredado)
googletag.defineSlot("/1234567/sports", [160, 600], "div").addService(googletag.pubads());
TypeScript
googletag.defineSlot("/1234567/sports", [160, 600], "div")!.addService(googletag.pubads());
- Consulta también
Parámetros | |
---|---|
service: Service | Es el servicio que se agregará. |
Muestra | |
---|---|
Slot | El objeto de inserción al que se llamó al método. |
clearCategoryExclusions
clearCategoryExclusions(): Slot
- Ejemplo
JavaScript
// Set category exclusion to exclude ads with 'AirlineAd' labels. const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setCategoryExclusion("AirlineAd") .addService(googletag.pubads()); // Make an ad request. No ad with 'AirlineAd' label will be returned // for the slot. // Clear category exclusions so all ads can be returned. slot.clearCategoryExclusions(); // Make an ad request. Any ad can be returned for the slot.
JavaScript (heredado)
// Set category exclusion to exclude ads with 'AirlineAd' labels. var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setCategoryExclusion("AirlineAd") .addService(googletag.pubads()); // Make an ad request. No ad with 'AirlineAd' label will be returned // for the slot. // Clear category exclusions so all ads can be returned. slot.clearCategoryExclusions(); // Make an ad request. Any ad can be returned for the slot.
TypeScript
// Set category exclusion to exclude ads with 'AirlineAd' labels. const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .setCategoryExclusion("AirlineAd") .addService(googletag.pubads()); // Make an ad request. No ad with 'AirlineAd' label will be returned // for the slot. // Clear category exclusions so all ads can be returned. slot.clearCategoryExclusions(); // Make an ad request. Any ad can be returned for the slot.
Muestra | |
---|---|
Slot | El objeto de inserción al que se llamó al método. |
clearTargeting
clearTargeting(key?: string): Slot
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setTargeting("allow_expandable", "true") .setTargeting("interests", ["sports", "music"]) .setTargeting("color", "red") .addService(googletag.pubads()); slot.clearTargeting("color"); // Targeting 'allow_expandable' and 'interests' are still present, // while 'color' was cleared. slot.clearTargeting(); // All targeting has been cleared.
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setTargeting("allow_expandable", "true") .setTargeting("interests", ["sports", "music"]) .setTargeting("color", "red") .addService(googletag.pubads()); slot.clearTargeting("color"); // Targeting 'allow_expandable' and 'interests' are still present, // while 'color' was cleared. slot.clearTargeting(); // All targeting has been cleared.
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .setTargeting("allow_expandable", "true") .setTargeting("interests", ["sports", "music"]) .setTargeting("color", "red") .addService(googletag.pubads()); slot.clearTargeting("color"); // Targeting 'allow_expandable' and 'interests' are still present, // while 'color' was cleared. slot.clearTargeting(); // All targeting has been cleared.
- Consulta también
Parámetros | |
---|---|
| Clave del parámetro de segmentación. La clave es opcional. Si no se especifica, se borrarán todos los parámetros de segmentación. |
Muestra | |
---|---|
Slot | El objeto de inserción al que se llamó al método. |
defineSizeMapping
defineSizeMapping(sizeMapping: SizeMappingArray): Slot
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); const mapping = googletag .sizeMapping() .addSize([100, 100], [88, 31]) .addSize( [320, 400], [ [320, 50], [300, 50], ], ) .build(); slot.defineSizeMapping(mapping);
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); var mapping = googletag .sizeMapping() .addSize([100, 100], [88, 31]) .addSize( [320, 400], [ [320, 50], [300, 50], ], ) .build(); slot.defineSizeMapping(mapping);
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); const mapping = googletag .sizeMapping() .addSize([100, 100], [88, 31]) .addSize( [320, 400], [ [320, 50], [300, 50], ], ) .build(); slot.defineSizeMapping(mapping!);
- Consulta también
Parámetros | |
---|---|
sizeMapping: SizeMappingArray | Array de asignaciones de tamaño. Puedes usar SizeMappingBuilder para crearlo. Cada asignación de tamaño es un array de dos elementos: SingleSizeArray y GeneralSize. |
Muestra | |
---|---|
Slot | El objeto de inserción al que se llamó al método. |
get
get(key: string): null | string
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .set("adsense_background_color", "#FFFFFF") .addService(googletag.pubads()); slot.get("adsense_background_color"); // Returns '#FFFFFF'.
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .set("adsense_background_color", "#FFFFFF") .addService(googletag.pubads()); slot.get("adsense_background_color"); // Returns '#FFFFFF'.
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .set("adsense_background_color", "#FFFFFF") .addService(googletag.pubads()); slot.get("adsense_background_color"); // Returns '#FFFFFF'.
- Consulta también
Parámetros | |
---|---|
key: string | Es el nombre del atributo que se debe buscar. |
Muestra | |
---|---|
null | string | Es el valor actual de la clave de atributo o null si la clave no está presente. |
getAdUnitPath
getAdUnitPath(): string
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); slot.getAdUnitPath(); // Returns '/1234567/sports'.
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); slot.getAdUnitPath(); // Returns '/1234567/sports'.
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); slot.getAdUnitPath(); // Returns '/1234567/sports'.
Muestra | |
---|---|
string | Ruta de acceso de la unidad de anuncios. |
getAttributeKeys
getAttributeKeys(): string[]
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .set("adsense_background_color", "#FFFFFF") .set("adsense_border_color", "#AABBCC") .addService(googletag.pubads()); slot.getAttributeKeys(); // Returns ['adsense_background_color', 'adsense_border_color'].
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .set("adsense_background_color", "#FFFFFF") .set("adsense_border_color", "#AABBCC") .addService(googletag.pubads()); slot.getAttributeKeys(); // Returns ['adsense_background_color', 'adsense_border_color'].
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .set("adsense_background_color", "#FFFFFF") .set("adsense_border_color", "#AABBCC") .addService(googletag.pubads()); slot.getAttributeKeys(); // Returns ['adsense_background_color', 'adsense_border_color'].
Muestra | |
---|---|
string[] | Es un array de claves de atributos. El orden no está definido. |
getCategoryExclusions
getCategoryExclusions(): string[]
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setCategoryExclusion("AirlineAd") .setCategoryExclusion("TrainAd") .addService(googletag.pubads()); slot.getCategoryExclusions(); // Returns ['AirlineAd', 'TrainAd'].
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setCategoryExclusion("AirlineAd") .setCategoryExclusion("TrainAd") .addService(googletag.pubads()); slot.getCategoryExclusions(); // Returns ['AirlineAd', 'TrainAd'].
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .setCategoryExclusion("AirlineAd") .setCategoryExclusion("TrainAd") .addService(googletag.pubads()); slot.getCategoryExclusions(); // Returns ['AirlineAd', 'TrainAd'].
Muestra | |
---|---|
string[] | Las etiquetas de exclusión de categorías de anuncios para este espacio o un array vacío si no se configuró ninguna. |
getResponseInformation
getResponseInformation(): null | ResponseInformation
null
.Muestra | |
---|---|
null | ResponseInformation | La información de respuesta de anuncios más reciente o null si el espacio no tiene anuncios. |
getSlotElementId
getSlotElementId(): string
div
de la ranura proporcionado cuando se definió la ranura.- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); slot.getSlotElementId(); // Returns 'div'.
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); slot.getSlotElementId(); // Returns 'div'.
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); slot.getSlotElementId(); // Returns 'div'.
Muestra | |
---|---|
string | ID de div de la ranura |
getTargeting
getTargeting(key: string): string[]
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setTargeting("allow_expandable", "true") .addService(googletag.pubads()); slot.getTargeting("allow_expandable"); // Returns ['true']. slot.getTargeting("age"); // Returns [] (empty array).
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setTargeting("allow_expandable", "true") .addService(googletag.pubads()); slot.getTargeting("allow_expandable"); // Returns ['true']. slot.getTargeting("age"); // Returns [] (empty array).
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .setTargeting("allow_expandable", "true") .addService(googletag.pubads()); slot.getTargeting("allow_expandable"); // Returns ['true']. slot.getTargeting("age"); // Returns [] (empty array).
Parámetros | |
---|---|
key: string | Es la clave de segmentación que se debe buscar. |
Muestra | |
---|---|
string[] | Los valores asociados con esta clave, o un array vacío si no hay tal clave. |
getTargetingKeys
getTargetingKeys(): string[]
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setTargeting("allow_expandable", "true") .setTargeting("interests", ["sports", "music"]) .addService(googletag.pubads()); slot.getTargetingKeys(); // Returns ['interests', 'allow_expandable'].
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setTargeting("allow_expandable", "true") .setTargeting("interests", ["sports", "music"]) .addService(googletag.pubads()); slot.getTargetingKeys(); // Returns ['interests', 'allow_expandable'].
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .setTargeting("allow_expandable", "true") .setTargeting("interests", ["sports", "music"]) .addService(googletag.pubads()); slot.getTargetingKeys(); // Returns ['interests', 'allow_expandable'].
Muestra | |
---|---|
string[] | Es un array de claves de segmentación. El orden no está definido. |
set
set(key: string, value: string): Slot
Si llamas a este método más de una vez para la misma clave, se anularán los valores establecidos anteriormente para esa clave. Todos los valores deben establecerse antes de llamar a
display
o refresh
.- Ejemplo
JavaScript
// Setting an attribute on a single ad slot. googletag .defineSlot("/1234567/sports", [160, 600], "div") .set("adsense_background_color", "#FFFFFF") .addService(googletag.pubads());
JavaScript (heredado)
// Setting an attribute on a single ad slot. googletag .defineSlot("/1234567/sports", [160, 600], "div") .set("adsense_background_color", "#FFFFFF") .addService(googletag.pubads());
TypeScript
// Setting an attribute on a single ad slot. googletag .defineSlot("/1234567/sports", [160, 600], "div")! .set("adsense_background_color", "#FFFFFF") .addService(googletag.pubads());
- Consulta también
Parámetros | |
---|---|
key: string | Es el nombre del atributo. |
value: string | Valor del atributo. |
Muestra | |
---|---|
Slot | El objeto de inserción al que se llamó al método. |
setCategoryExclusion
setCategoryExclusion(categoryExclusion: string): Slot
- Ejemplo
JavaScript
// Label = AirlineAd googletag .defineSlot("/1234567/sports", [160, 600], "div") .setCategoryExclusion("AirlineAd") .addService(googletag.pubads());
JavaScript (heredado)
// Label = AirlineAd googletag .defineSlot("/1234567/sports", [160, 600], "div") .setCategoryExclusion("AirlineAd") .addService(googletag.pubads());
TypeScript
// Label = AirlineAd googletag .defineSlot("/1234567/sports", [160, 600], "div")! .setCategoryExclusion("AirlineAd") .addService(googletag.pubads());
- Consulta también
Parámetros | |
---|---|
categoryExclusion: string | La etiqueta de exclusión de categoría de anuncios que deseas agregar. |
Muestra | |
---|---|
Slot | El objeto de inserción al que se llamó al método. |
setClickUrl
setClickUrl(value: string): Slot
Los servidores de Google Ad Manager siguen registrando un clic, incluso si se reemplaza la URL de clic. Cualquier URL de página de destino asociada con la creatividad que se publica se adjunta al valor proporcionado. Las llamadas posteriores reemplazan el valor. Esto solo funciona para solicitudes que no sean de SRA.
- Ejemplo
JavaScript
googletag .defineSlot("/1234567/sports", [160, 600], "div") .setClickUrl("http://www.example.com?original_click_url=") .addService(googletag.pubads());
JavaScript (heredado)
googletag .defineSlot("/1234567/sports", [160, 600], "div") .setClickUrl("http://www.example.com?original_click_url=") .addService(googletag.pubads());
TypeScript
googletag .defineSlot("/1234567/sports", [160, 600], "div")! .setClickUrl("http://www.example.com?original_click_url=") .addService(googletag.pubads());
Parámetros | |
---|---|
value: string | Es la URL de clic que se debe establecer. |
Muestra | |
---|---|
Slot | El objeto de inserción al que se llamó al método. |
setCollapseEmptyDiv
setCollapseEmptyDiv(collapse: boolean, collapseBeforeAdFetch?: boolean): Slot
div
cuando no hay un anuncio en él. Esto anula la configuración a nivel del servicio.- Ejemplo
JavaScript
googletag .defineSlot("/1234567/sports", [160, 600], "div-1") .setCollapseEmptyDiv(true, true) .addService(googletag.pubads()); // The above will cause the div for this slot to be collapsed // when the page is loaded, before ads are requested. googletag .defineSlot("/1234567/sports", [160, 600], "div-2") .setCollapseEmptyDiv(true) .addService(googletag.pubads()); // The above will cause the div for this slot to be collapsed // only after GPT detects that no ads are available for the slot.
JavaScript (heredado)
googletag .defineSlot("/1234567/sports", [160, 600], "div-1") .setCollapseEmptyDiv(true, true) .addService(googletag.pubads()); // The above will cause the div for this slot to be collapsed // when the page is loaded, before ads are requested. googletag .defineSlot("/1234567/sports", [160, 600], "div-2") .setCollapseEmptyDiv(true) .addService(googletag.pubads()); // The above will cause the div for this slot to be collapsed // only after GPT detects that no ads are available for the slot.
TypeScript
googletag .defineSlot("/1234567/sports", [160, 600], "div-1")! .setCollapseEmptyDiv(true, true) .addService(googletag.pubads()); // The above will cause the div for this slot to be collapsed // when the page is loaded, before ads are requested. googletag .defineSlot("/1234567/sports", [160, 600], "div-2")! .setCollapseEmptyDiv(true) .addService(googletag.pubads()); // The above will cause the div for this slot to be collapsed // only after GPT detects that no ads are available for the slot.
Parámetros | |
---|---|
collapse: boolean | Indica si se debe contraer el espacio si no se muestra ningún anuncio. |
| Indica si se debe contraer el espacio publicitario incluso antes de que se recupere un anuncio. Se ignora si el colapso no es true . |
Muestra | |
---|---|
Slot | El objeto de inserción al que se llamó al método. |
setConfig
setConfig(slotConfig: SlotSettingsConfig): void
Parámetros | |
---|---|
slotConfig: SlotSettingsConfig | El objeto de configuración |
setForceSafeFrame
setForceSafeFrame(forceSafeFrame: boolean): Slot
Ten en cuenta lo siguiente cuando uses esta API:
- Este parámetro de configuración solo tendrá efecto en las solicitudes de anuncios posteriores que se realicen para los respectivos espacios.
- Si se especifica, la configuración a nivel del espacio siempre anulará la configuración a nivel de la página.
- Si se establece en
true
(a nivel del espacio o de la página), el anuncio siempre se renderizará con un contenedor de SafeFrame, independientemente de la opción que se elija en la IU de Google Ad Manager. - Sin embargo, si se establece en
false
o no se especifica, el anuncio se renderizará con un contenedor de SafeFrame según el tipo de creatividad y la selección que se realice en la IU de Google Ad Manager. - Esta API se debe usar con precaución, ya que podría afectar el comportamiento de las creatividades que intentan salir de sus iframes o dependen de que se rendericen directamente en una página del publicador.
- Ejemplo
JavaScript
googletag .defineSlot("/1234567/sports", [160, 600], "div") .setForceSafeFrame(true) .addService(googletag.pubads());
JavaScript (heredado)
googletag .defineSlot("/1234567/sports", [160, 600], "div") .setForceSafeFrame(true) .addService(googletag.pubads());
TypeScript
googletag .defineSlot("/1234567/sports", [160, 600], "div")! .setForceSafeFrame(true) .addService(googletag.pubads());
- Consulta también
Parámetros | |
---|---|
forceSafeFrame: boolean | true para forzar que todos los anuncios de este espacio se rendericen en SafeFrames y false para inhabilitar un parámetro de configuración a nivel de la página (si está presente). Si no se especifica a nivel de la página, establecerlo en false no cambiará nada. |
Muestra | |
---|---|
Slot | El objeto de inserción al que se llamó al método. |
setSafeFrameConfig
setSafeFrameConfig(config: null | SafeFrameConfig): Slot
Si se especifican, estas preferencias a nivel del espacio anularán cualquier preferencia a nivel de la página.
- Ejemplo
JavaScript
googletag.pubads().setForceSafeFrame(true); // The following slot will have a sandboxed safeframe that only // disallows top-level navigation. googletag .defineSlot("/1234567/sports", [160, 600], "div-1") .setSafeFrameConfig({ sandbox: true }) .addService(googletag.pubads()); // The following slot will inherit page-level settings. googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads()); googletag.display("div-1"); googletag.display("div-2");
JavaScript (heredado)
googletag.pubads().setForceSafeFrame(true); // The following slot will have a sandboxed safeframe that only // disallows top-level navigation. googletag .defineSlot("/1234567/sports", [160, 600], "div-1") .setSafeFrameConfig({ sandbox: true }) .addService(googletag.pubads()); // The following slot will inherit page-level settings. googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads()); googletag.display("div-1"); googletag.display("div-2");
TypeScript
googletag.pubads().setForceSafeFrame(true); // The following slot will have a sandboxed safeframe that only // disallows top-level navigation. googletag .defineSlot("/1234567/sports", [160, 600], "div-1")! .setSafeFrameConfig({ sandbox: true }) .addService(googletag.pubads()); // The following slot will inherit page-level settings. googletag.defineSlot("/1234567/news", [160, 600], "div-2")!.addService(googletag.pubads()); googletag.display("div-1"); googletag.display("div-2");
- Consulta también
Parámetros | |
---|---|
config: null | SafeFrameConfig | El objeto de configuración |
Muestra | |
---|---|
Slot | El objeto de inserción al que se llamó al método. |
setTargeting
setTargeting(key: string, value: string | string[]): Slot
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Example with a single value for a key. slot.setTargeting("allow_expandable", "true"); // Example with multiple values for a key inside in an array. slot.setTargeting("interests", ["sports", "music"]);
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Example with a single value for a key. slot.setTargeting("allow_expandable", "true"); // Example with multiple values for a key inside in an array. slot.setTargeting("interests", ["sports", "music"]);
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); // Example with a single value for a key. slot.setTargeting("allow_expandable", "true"); // Example with multiple values for a key inside in an array. slot.setTargeting("interests", ["sports", "music"]);
- Consulta también
Parámetros | |
---|---|
key: string | Clave del parámetro de segmentación. |
value: string | string[] | Valor o array de valores del parámetro de segmentación |
Muestra | |
---|---|
Slot | El objeto de inserción al que se llamó al método. |
updateTargetingFromMap
updateTargetingFromMap(map: {
[adUnitPath: string]: string | string[];
}): Slot
Notas:
- En caso de reemplazo, solo se conservará el último valor.
- Si el valor es un array, se reemplazará cualquier valor anterior, no se combinará.
- Los valores que se establezcan aquí reemplazarán los parámetros de segmentación establecidos a nivel del servicio.
- Ejemplo
JavaScript
const slot = googletag.defineSlot("/1234567/sports", [160, 600], "div"); slot.updateTargetingFromMap({ color: "red", interests: ["sports", "music", "movies"], });
JavaScript (heredado)
var slot = googletag.defineSlot("/1234567/sports", [160, 600], "div"); slot.updateTargetingFromMap({ color: "red", interests: ["sports", "music", "movies"], });
TypeScript
const slot = googletag.defineSlot("/1234567/sports", [160, 600], "div")!; slot.updateTargetingFromMap({ color: "red", interests: ["sports", "music", "movies"], });
Parámetros | |
---|---|
map: { | Mapa de par clave-valor del parámetro de segmentación. |
Muestra | |
---|---|
Slot | El objeto de inserción al que se llamó al método. |
googletag.config
Interfaces | |
---|---|
Ad | Configuración para controlar la expansión de anuncios. |
Component | Es un objeto que representa una subasta de un solo componente en una subasta de anuncios integrada en el dispositivo. |
Interstitial | Es un objeto que define el comportamiento de un solo espacio publicitario intersticial. |
Page | Interfaz de configuración principal para la configuración a nivel de la página. |
Privacy | Configuración para controlar los tratamientos de privacidad de los publicadores |
Publisher | Objeto de configuración de indicadores proporcionados por el publicador (PPS). |
Slot | Interfaz de configuración principal para la configuración a nivel de la ranura. |
Taxonomy | Es un objeto que contiene los valores de una sola taxonomía. |
Alias de tipo | |
---|---|
Interstitial | Activadores de anuncios intersticiales compatibles |
Privacy | Tratamientos de privacidad del publicador admitidos |
Taxonomy | Taxonomías admitidas para los indicadores proporcionados por el publicador (PPS). |
Alias de tipo
InterstitialTrigger
InterstitialTrigger: "unhideWindow" | "navBar"
PrivacyTreatment
PrivacyTreatment: "disablePersonalization"
Taxonomía
Taxonomy: "IAB_AUDIENCE_1_1" | "IAB_CONTENT_2_2"
- Consulta también
googletag.config.AdExpansionConfig
Propiedades | |
---|---|
enabled | Indica si la expansión de anuncios está habilitada o inhabilitada. |
- Ejemplo
JavaScript
// Enable ad slot expansion across the entire page. googletag.setConfig({ adExpansion: { enabled: true }, });
JavaScript (heredado)
// Enable ad slot expansion across the entire page. googletag.setConfig({ adExpansion: { enabled: true }, });
TypeScript
// Enable ad slot expansion across the entire page. googletag.setConfig({ adExpansion: { enabled: true }, });
Propiedades
Optional
habilitado
enabled?: null | boolean
Si estableces este valor, se anula el valor predeterminado configurado en Google Ad Manager.
googletag.config.ComponentAuctionConfig
Propiedades | |
---|---|
auction | Un objeto de configuración de subasta para esta subasta de componentes. |
config | Es la clave de configuración asociada con esta subasta de componentes. |
Propiedades
auctionConfig
auctionConfig: null | {
auctionSignals?: unknown;
decisionLogicURL: string;
interestGroupBuyers?: string[];
perBuyerExperimentGroupIds?: {
[buyer: string]: number;
};
perBuyerGroupLimits?: {
[buyer: string]: number;
};
perBuyerSignals?: {
[buyer: string]: unknown;
};
perBuyerTimeouts?: {
[buyer: string]: number;
};
seller: string;
sellerExperimentGroupId?: number;
sellerSignals?: unknown;
sellerTimeout?: number;
trustedScoringSignalsURL?: string;
}
Si este valor se establece en
null
, se borrará cualquier configuración existente para el configKey
especificado.- Ejemplo
JavaScript
const componentAuctionConfig = { // Seller URL should be https and the same as decisionLogicURL's origin seller: "https://testSeller.com", decisionLogicURL: "https://testSeller.com/ssp/decision-logic.js", interestGroupBuyers: ["https://example-buyer.com"], auctionSignals: { auction_signals: "auction_signals" }, sellerSignals: { seller_signals: "seller_signals" }, perBuyerSignals: { // listed on interestGroupBuyers "https://example-buyer.com": { per_buyer_signals: "per_buyer_signals", }, }, }; const auctionSlot = googletag.defineSlot("/1234567/example", [160, 600]); // To add configKey to the component auction: auctionSlot.setConfig({ componentAuction: [ { configKey: "https://testSeller.com", auctionConfig: componentAuctionConfig, }, ], }); // To remove configKey from the component auction: auctionSlot.setConfig({ componentAuction: [ { configKey: "https://testSeller.com", auctionConfig: null, }, ], });
JavaScript (heredado)
var componentAuctionConfig = { // Seller URL should be https and the same as decisionLogicURL's origin seller: "https://testSeller.com", decisionLogicURL: "https://testSeller.com/ssp/decision-logic.js", interestGroupBuyers: ["https://example-buyer.com"], auctionSignals: { auction_signals: "auction_signals" }, sellerSignals: { seller_signals: "seller_signals" }, perBuyerSignals: { // listed on interestGroupBuyers "https://example-buyer.com": { per_buyer_signals: "per_buyer_signals", }, }, }; var auctionSlot = googletag.defineSlot("/1234567/example", [160, 600]); // To add configKey to the component auction: auctionSlot.setConfig({ componentAuction: [ { configKey: "https://testSeller.com", auctionConfig: componentAuctionConfig, }, ], }); // To remove configKey from the component auction: auctionSlot.setConfig({ componentAuction: [ { configKey: "https://testSeller.com", auctionConfig: null, }, ], });
TypeScript
const componentAuctionConfig = { // Seller URL should be https and the same as decisionLogicURL's origin seller: "https://testSeller.com", decisionLogicURL: "https://testSeller.com/ssp/decision-logic.js", interestGroupBuyers: ["https://example-buyer.com"], auctionSignals: { auction_signals: "auction_signals" }, sellerSignals: { seller_signals: "seller_signals" }, perBuyerSignals: { // listed on interestGroupBuyers "https://example-buyer.com": { per_buyer_signals: "per_buyer_signals", }, }, }; const auctionSlot = googletag.defineSlot("/1234567/example", [160, 600])!; // To add configKey to the component auction: auctionSlot.setConfig({ componentAuction: [ { configKey: "https://testSeller.com", auctionConfig: componentAuctionConfig, }, ], }); // To remove configKey from the component auction: auctionSlot.setConfig({ componentAuction: [ { configKey: "https://testSeller.com", auctionConfig: null, }, ], });
configKey
configKey: string
Este valor no debe estar vacío y debe ser único. Si dos objetos
ComponentAuctionConfig
comparten el mismo valor de configKey, el último que se establezca reemplazará las configuraciones anteriores.googletag.config.InterstitialConfig
Propiedades | |
---|---|
require | Indica si se requiere el consentimiento de almacenamiento local para mostrar este anuncio intersticial. |
triggers | Es la configuración del activador intersticial para este anuncio intersticial. |
Propiedades
Optional
requireStorageAccess
requireStorageAccess?: null | boolean
GPT usa el almacenamiento local para aplicar una limitación de frecuencia para los anuncios intersticiales. Sin embargo, los usuarios que no proporcionaron el consentimiento de almacenamiento local aún son aptos para que se les muestren anuncios intersticiales. Si estableces esta propiedad en
true
, se inhabilita el comportamiento predeterminado y se garantiza que los anuncios intersticiales solo se muestren a los usuarios que hayan otorgado su consentimiento para el almacenamiento local.- Ejemplo
JavaScript
// Opt out of showing interstitials to users // without local storage consent. const interstitialSlot = googletag.defineOutOfPageSlot( "/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL, ); interstitialSlot.setConfig({ interstitial: { requireStorageAccess: true, // defaults to false }, });
JavaScript (heredado)
// Opt out of showing interstitials to users // without local storage consent. var interstitialSlot = googletag.defineOutOfPageSlot( "/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL, ); interstitialSlot.setConfig({ interstitial: { requireStorageAccess: true, // defaults to false }, });
TypeScript
// Opt out of showing interstitials to users // without local storage consent. const interstitialSlot = googletag.defineOutOfPageSlot( "/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL, )!; interstitialSlot.setConfig({ interstitial: { requireStorageAccess: true, // defaults to false }, });
- Consulta también
Optional
activadores
triggers?: null | Partial<Record<InterstitialTrigger, boolean>>
Si estableces el valor de un activador de anuncios intersticiales en
true
, se habilitará, y si lo estableces en false
, se inhabilitará. Esto anulará los valores predeterminados configurados en Google Ad Manager.- Ejemplo
JavaScript
// Define a GPT managed web interstitial ad slot. const interstitialSlot = googletag.defineOutOfPageSlot( "/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL, ); // Enable optional interstitial triggers. // Change this value to false to disable. const enableTriggers = true; interstitialSlot.setConfig({ interstitial: { triggers: { navBar: enableTriggers, unhideWindow: enableTriggers, }, }, });
JavaScript (heredado)
// Define a GPT managed web interstitial ad slot. var interstitialSlot = googletag.defineOutOfPageSlot( "/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL, ); // Enable optional interstitial triggers. // Change this value to false to disable. var enableTriggers = true; interstitialSlot.setConfig({ interstitial: { triggers: { navBar: enableTriggers, unhideWindow: enableTriggers, }, }, });
TypeScript
// Define a GPT managed web interstitial ad slot. const interstitialSlot = googletag.defineOutOfPageSlot( "/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL, )!; // Enable optional interstitial triggers. // Change this value to false to disable. const enableTriggers = true; interstitialSlot.setConfig({ interstitial: { triggers: { navBar: enableTriggers, unhideWindow: enableTriggers, }, }, });
- Consulta también
googletag.config.PageSettingsConfig
Permite configurar varias funciones con una sola llamada a la API.
Todas las propiedades que se enumeran a continuación son ejemplos y no reflejan las funciones reales que utilizan setConfig. Para el conjunto de atributos, consulta los campos dentro del tipo PageSettingsConfig a continuación.
Ejemplos:
- Solo se modifican las funciones especificadas en la llamada googletag.setConfig.
// Configure feature alpha. googletag.setConfig({ alpha: {...} }); // Configure feature bravo. Feature alpha is unchanged. googletag.setConfig({ bravo: {...} });
- Todos los parámetros de configuración de una función determinada se actualizan con cada llamada a googletag.setConfig.
// Configure feature charlie to echo = 1, foxtrot = true. googletag.setConfig({ charlie: { echo: 1, foxtrot: true, } }); // Update feature charlie to echo = 2. Since foxtrot was not specified, // the value is cleared. googletag.setConfig({ charlie: { echo: 2 } });
- Para borrar todos los parámetros de configuración de una función, pasa
null
.// Configure features delta, golf, and hotel. googletag.setConfig({ delta: {...}, golf: {...}, hotel: {...}, }); // Feature delta and hotel are cleared, but feature golf remains set. googletag.setConfig({ delta: null, hotel: null, });
Propiedades | |
---|---|
ad | Configuración para controlar la expansión de anuncios. |
ad | Obsoleto. |
pps | Configuración para controlar los indicadores proporcionados por el publicador (PPS). |
privacy | Configuración para controlar los tratamientos de privacidad de los publicadores |
thread | Configuración para controlar si GPT debe generar el subproceso de JS cuando se renderizan las creatividades. |
Propiedades
Optional
adExpansion
adExpansion?: null | AdExpansionConfig
Optional
adYield
adYield?: null | "DISABLED" | "ENABLED_ALL_SLOTS"
Optional
pps
pps?: null | PublisherProvidedSignalsConfig
Optional
privacyTreatments
privacyTreatments?: null | PrivacyTreatmentsConfig
Optional
threadYield
threadYield?: null | "DISABLED" | "ENABLED_ALL_SLOTS"
GPT solo se generará para los navegadores que admitan la API de Scheduler.postTask o Scheduler.yield.
Valores admitidos:
null
(predeterminada): GPT generará el subproceso de JS para los espacios fuera del viewport.ENABLED_ALL_SLOTS
: GPT generará el subproceso de JS para todos los espacios, independientemente de si el espacio está dentro del viewport.DISABLED
: GPT no generará el subproceso de JS.
- Ejemplo
JavaScript
// Disable yielding. googletag.setConfig({ threadYield: "DISABLED" }); // Enable yielding for all slots. googletag.setConfig({ threadYield: "ENABLED_ALL_SLOTS" }); // Enable yielding only for slots outside of the viewport (default). googletag.setConfig({ threadYield: null });
JavaScript (heredado)
// Disable yielding. googletag.setConfig({ threadYield: "DISABLED" }); // Enable yielding for all slots. googletag.setConfig({ threadYield: "ENABLED_ALL_SLOTS" }); // Enable yielding only for slots outside of the viewport (default). googletag.setConfig({ threadYield: null });
TypeScript
// Disable yielding. googletag.setConfig({ threadYield: "DISABLED" }); // Enable yielding for all slots. googletag.setConfig({ threadYield: "ENABLED_ALL_SLOTS" }); // Enable yielding only for slots outside of the viewport (default). googletag.setConfig({ threadYield: null });
- Consulta también
googletag.config.PrivacyTreatmentsConfig
Propiedades | |
---|---|
treatments | Es un array de tratamientos de privacidad del publicador que se deben habilitar. |
Propiedades
tratamientos
treatments: null | "disablePersonalization"[]
- Ejemplo
JavaScript
// Disable personalization across the entire page. googletag.setConfig({ privacyTreatments: { treatments: ["disablePersonalization"] }, });
JavaScript (heredado)
// Disable personalization across the entire page. googletag.setConfig({ privacyTreatments: { treatments: ["disablePersonalization"] }, });
TypeScript
// Disable personalization across the entire page. googletag.setConfig({ privacyTreatments: { treatments: ["disablePersonalization"] }, });
googletag.config.PublisherProvidedSignalsConfig
Propiedades | |
---|---|
taxonomies | Es un objeto que contiene asignaciones de taxonomía. |
- Ejemplo
JavaScript
googletag.setConfig({ pps: { taxonomies: { IAB_AUDIENCE_1_1: { values: ["6", "626"] }, // '6' = 'Demographic | Age Range | 30-34' // '626' = 'Interest | Sports | Darts' IAB_CONTENT_2_2: { values: ["48", "127"] }, // '48' = 'Books and Literature | Fiction' // '127' = 'Careers | Job Search' }, }, });
JavaScript (heredado)
googletag.setConfig({ pps: { taxonomies: { IAB_AUDIENCE_1_1: { values: ["6", "626"] }, // '6' = 'Demographic | Age Range | 30-34' // '626' = 'Interest | Sports | Darts' IAB_CONTENT_2_2: { values: ["48", "127"] }, // '48' = 'Books and Literature | Fiction' // '127' = 'Careers | Job Search' }, }, });
TypeScript
googletag.setConfig({ pps: { taxonomies: { IAB_AUDIENCE_1_1: { values: ["6", "626"] }, // '6' = 'Demographic | Age Range | 30-34' // '626' = 'Interest | Sports | Darts' IAB_CONTENT_2_2: { values: ["48", "127"] }, // '48' = 'Books and Literature | Fiction' // '127' = 'Careers | Job Search' }, }, });
Propiedades
taxonomías
taxonomies: Partial<Record<Taxonomy, TaxonomyData>>
googletag.config.SlotSettingsConfig
Permite configurar varias funciones con una sola llamada a la API para un solo zócalo.
Todas las propiedades que se enumeran a continuación son ejemplos y no reflejan las funciones reales que utilizan setConfig. Para el conjunto de atributos, consulta los campos dentro del tipo SlotSettingsConfig a continuación.
Ejemplos:
- Solo se modifican los atributos especificados en la llamada Slot.setConfig.
const slot = googletag.defineSlot("/1234567/example", [160, 600]); // Configure feature alpha. slot.setConfig({ alpha: {...} }); // Configure feature bravo. Feature alpha is unchanged. slot.setConfig({ bravo: {...} });
- Todos los parámetros de configuración de una función determinada se actualizan con cada llamada a Slot.setConfig.
// Configure feature charlie to echo = 1, foxtrot = true. slot.setConfig({ charlie: { echo: 1, foxtrot: true, } }); // Update feature charlie to echo = 2. Since foxtrot was not specified, // the value is cleared. slot.setConfig({ charlie: { echo: 2 } });
- Para borrar todos los parámetros de configuración de una función, pasa
null
.// Configure features delta, golf, and hotel. slot.setConfig({ delta: {...}, golf: {...}, hotel: {...}, }); // Feature delta and hotel are cleared, but feature golf remains set. slot.setConfig({ delta: null, hotel: null, });
Propiedades | |
---|---|
ad | Configuración para controlar la expansión de anuncios. |
component | Es un array de subastas de componentes que se incluirán en una subasta de anuncios integrada en el dispositivo. |
interstitial | Configuración que controla el comportamiento de los espacios publicitarios intersticiales. |
Propiedades
Optional
adExpansion
adExpansion?: null | AdExpansionConfig
Optional
componentAuction
componentAuction?: null | ComponentAuctionConfig[]
Optional
intersticial
interstitial?: null | InterstitialConfig
googletag.config.TaxonomyData
Propiedades | |
---|---|
values | Es una lista de valores de taxonomía. |
Propiedades
values
values: string[]
googletag.enums
Enumeraciones | |
---|---|
Out | Formatos fuera de página compatibles con GPT |
Traffic | Fuentes de tráfico compatibles con GPT. |
Enumeraciones
OutOfPageFormat
OutOfPageFormat
- Consulta también
Miembros de enumeración | |
---|---|
BOTTOM_ | Es el formato de anclaje en el que el espacio se pega a la parte inferior del viewport. |
GAME_ | Formato de anuncio intersticial manual del juego. Nota: El anuncio intersticial manual del juego es un formato de acceso limitado. |
INTERSTITIAL | Formato de creatividad intersticial web |
LEFT_ | Formato del anuncio lateral izquierdo. |
REWARDED | Formato recompensado. |
RIGHT_ | Formato del anuncio lateral derecho. |
TOP_ | Es el formato de anclaje en el que el espacio publicitario se pega a la parte superior del viewport. |
TrafficSource
TrafficSource
- Consulta también
googletag.events
Interfaces | |
---|---|
Event | Es la interfaz base para todos los eventos de GPT. |
Event | Este es un pseudotipo que asigna un nombre de evento a su tipo de objeto de evento correspondiente para Service.addEventListener y Service.removeEventListener. |
Game | Este evento se activa cuando el usuario cierra un espacio intersticial manual de un juego. |
Game | Este evento se activa cuando un espacio intersticial manual de juegos está listo para mostrarse al usuario. |
Impression | Este evento se activa cuando una impresión se vuelve visible, según los criterios de Vista activa. |
Rewarded | Este evento se activa cuando el usuario cierra un espacio de anuncios recompensados. |
Rewarded | Este evento se activa cuando se otorga una recompensa por ver un anuncio recompensado. |
Rewarded | Este evento se activa cuando un anuncio recompensado está listo para mostrarse. |
Slot | Este evento se activa cuando el iframe de la creatividad activa su evento de carga. |
Slot | Este evento se activa cuando el código de la creatividad se inserta en un espacio. |
Slot | Este evento se activa cuando se solicita un anuncio para un espacio publicitario en particular. |
Slot | Este evento se activa cuando se recibe una respuesta de anuncio para un espacio en particular. |
Slot | Este evento se activa cada vez que cambia el porcentaje en pantalla del área de un espacio de anuncios. |
googletag.events.Event
Propiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. |
slot | Es el espacio que activó el evento. |
- Consulta también
Propiedades
serviceName
serviceName: string
ranura
slot: Slot
googletag.events.EventTypeMap
Propiedades | |
---|---|
game | Es un alias de events.GameManualInterstitialSlotClosedEvent. |
game | Es un alias de events.GameManualInterstitialSlotReadyEvent. |
impression | Es un alias de events.ImpressionViewableEvent. |
rewarded | Es un alias de events.RewardedSlotClosedEvent. |
rewarded | Es un alias de events.RewardedSlotGrantedEvent. |
rewarded | Es un alias de events.RewardedSlotReadyEvent. |
slot | Es un alias de events.SlotOnloadEvent. |
slot | Es un alias de events.SlotRenderEndedEvent. |
slot | Es un alias de events.SlotRequestedEvent. |
slot | Es un alias de events.SlotResponseReceived. |
slot | Es un alias de events.SlotVisibilityChangedEvent. |
Propiedades
gameManualInterstitialSlotClosed
gameManualInterstitialSlotClosed: GameManualInterstitialSlotClosedEvent
gameManualInterstitialSlotReady
gameManualInterstitialSlotReady: GameManualInterstitialSlotReadyEvent
impressionViewable
impressionViewable: ImpressionViewableEvent
rewardedSlotClosed
rewardedSlotClosed: RewardedSlotClosedEvent
rewardedSlotGranted
rewardedSlotGranted: RewardedSlotGrantedEvent
rewardedSlotReady
rewardedSlotReady: RewardedSlotReadyEvent
slotOnload
slotOnload: SlotOnloadEvent
slotRenderEnded
slotRenderEnded: SlotRenderEndedEvent
slotRequested
slotRequested: SlotRequestedEvent
slotResponseReceived
slotResponseReceived: SlotResponseReceived
slotVisibilityChanged
slotVisibilityChanged: SlotVisibilityChangedEvent
googletag.events.GameManualInterstitialSlotClosedEvent
ExtiendeNota: El intersticial manual en el juego es un formato de acceso limitado.
Propiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. Se heredó de |
slot | Es el espacio que activó el evento. Se heredó de |
- Ejemplo
JavaScript
// This listener is called when a game manual interstitial slot is closed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotClosed", (event) => { const slot = event.slot; console.log("Game manual interstital slot", slot.getSlotElementId(), "is closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (heredado)
// This listener is called when a game manual interstitial slot is closed. var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotClosed", function (event) { var slot = event.slot; console.log("Game manual interstital slot", slot.getSlotElementId(), "is closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
// This listener is called when a game manual interstitial slot is closed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotClosed", (event) => { const slot = event.slot; console.log("Game manual interstital slot", slot.getSlotElementId(), "is closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
googletag.events.GameManualInterstitialSlotReadyEvent
ExtiendeNota: El anuncio intersticial manual en juegos es un formato de acceso limitado.
Propiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. Se heredó de |
slot | Es el espacio que activó el evento. Se heredó de |
Métodos | |
---|---|
make | Muestra el anuncio intersticial manual en juegos al usuario. |
- Ejemplo
JavaScript
// This listener is called when a game manual interstitial slot is ready to // be displayed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotReady", (event) => { const slot = event.slot; console.log( "Game manual interstital slot", slot.getSlotElementId(), "is ready to be displayed.", ); // Replace with custom logic. const displayGmiAd = true; if (displayGmiAd) { event.makeGameManualInterstitialVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (heredado)
// This listener is called when a game manual interstitial slot is ready to // be displayed. var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotReady", function (event) { var slot = event.slot; console.log( "Game manual interstital slot", slot.getSlotElementId(), "is ready to be displayed.", ); // Replace with custom logic. var displayGmiAd = true; if (displayGmiAd) { event.makeGameManualInterstitialVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
// This listener is called when a game manual interstitial slot is ready to // be displayed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotReady", (event) => { const slot = event.slot; console.log( "Game manual interstital slot", slot.getSlotElementId(), "is ready to be displayed.", ); // Replace with custom logic. const displayGmiAd = true; if (displayGmiAd) { event.makeGameManualInterstitialVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
Métodos
makeGameManualInterstitialVisible
makeGameManualInterstitialVisible(): void
googletag.events.ImpressionViewableEvent
ExtiendePropiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. Se heredó de |
slot | Es el espacio que activó el evento. Se heredó de |
- Ejemplo
JavaScript
// This listener is called when an impression becomes viewable. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("impressionViewable", (event) => { const slot = event.slot; console.log("Impression for slot", slot.getSlotElementId(), "became viewable."); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (heredado)
// This listener is called when an impression becomes viewable. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("impressionViewable", function (event) { var slot = event.slot; console.log("Impression for slot", slot.getSlotElementId(), "became viewable."); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called when an impression becomes viewable. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("impressionViewable", (event) => { const slot = event.slot; console.log("Impression for slot", slot.getSlotElementId(), "became viewable."); if (slot === targetSlot) { // Slot specific logic. } });
- Consulta también
googletag.events.RewardedSlotClosedEvent
ExtiendePropiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. Se heredó de |
slot | Es el espacio que activó el evento. Se heredó de |
- Ejemplo
JavaScript
const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called when the user closes a rewarded ad slot. googletag.pubads().addEventListener("rewardedSlotClosed", (event) => { const slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "has been closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (heredado)
var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called when the user closes a rewarded ad slot. googletag.pubads().addEventListener("rewardedSlotClosed", function (event) { var slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "has been closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called when the user closes a rewarded ad slot. googletag.pubads().addEventListener("rewardedSlotClosed", (event) => { const slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "has been closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
googletag.events.RewardedSlotGrantedEvent
ExtiendePropiedades | |
---|---|
payload | Es un objeto que contiene información sobre la recompensa que se otorgó. |
service | Es el nombre del servicio que activó el evento. Se heredó de |
slot | Es el espacio que activó el evento. Se heredó de |
- Ejemplo
JavaScript
const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotGranted", (event) => { const slot = event.slot; console.group("Reward granted for slot", slot.getSlotElementId(), "."); // Log details of the reward. console.log("Reward type:", event.payload?.type); console.log("Reward amount:", event.payload?.amount); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (heredado)
var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotGranted", function (event) { var _a, _b; var slot = event.slot; console.group("Reward granted for slot", slot.getSlotElementId(), "."); // Log details of the reward. console.log("Reward type:", (_a = event.payload) === null || _a === void 0 ? void 0 : _a.type); console.log( "Reward amount:", (_b = event.payload) === null || _b === void 0 ? void 0 : _b.amount, ); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotGranted", (event) => { const slot = event.slot; console.group("Reward granted for slot", slot.getSlotElementId(), "."); // Log details of the reward. console.log("Reward type:", event.payload?.type); console.log("Reward amount:", event.payload?.amount); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } }); }
Propiedades
carga útil
payload: null | RewardedPayload
googletag.events.RewardedSlotReadyEvent
ExtiendePropiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. Se heredó de |
slot | Es el espacio que activó el evento. Se heredó de |
Métodos | |
---|---|
make | Muestra el anuncio recompensado. |
- Ejemplo
JavaScript
// This listener is called when a rewarded ad slot becomes ready to be // displayed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotReady", (event) => { const slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed."); // Replace with custom logic. const userHasConsented = true; if (userHasConsented) { event.makeRewardedVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (heredado)
// This listener is called when a rewarded ad slot becomes ready to be // displayed. var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotReady", function (event) { var slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed."); // Replace with custom logic. var userHasConsented = true; if (userHasConsented) { event.makeRewardedVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
// This listener is called when a rewarded ad slot becomes ready to be // displayed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotReady", (event) => { const slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed."); // Replace with custom logic. const userHasConsented = true; if (userHasConsented) { event.makeRewardedVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
Métodos
makeRewardedVisible
makeRewardedVisible(): void
googletag.events.SlotOnloadEvent
ExtiendeSlotOnloadEvent
.Propiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. Se heredó de |
slot | Es el espacio que activó el evento. Se heredó de |
- Ejemplo
JavaScript
// This listener is called when a creative iframe load event fires. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", (event) => { const slot = event.slot; console.log("Creative iframe for slot", slot.getSlotElementId(), "has loaded."); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (heredado)
// This listener is called when a creative iframe load event fires. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", function (event) { var slot = event.slot; console.log("Creative iframe for slot", slot.getSlotElementId(), "has loaded."); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called when a creative iframe load event fires. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", (event) => { const slot = event.slot; console.log("Creative iframe for slot", slot.getSlotElementId(), "has loaded."); if (slot === targetSlot) { // Slot specific logic. } });
- Consulta también
googletag.events.SlotRenderEndedEvent
ExtiendePropiedades | |
---|---|
advertiser | Es el ID del anunciante del anuncio renderizado. |
campaign | Es el ID de la campaña del anuncio renderizado. |
company | Son los IDs de las empresas que ofertan en el anuncio de reabastecimiento renderizado. |
creative | Es el ID de la creatividad del anuncio de reserva renderizado. |
creative | Es el ID de la plantilla de creatividad del anuncio de reserva renderizado. |
is | Indica si un anuncio fue de reabastecimiento. |
is | Indica si se mostró un anuncio para el espacio. |
label | Obsoleto. |
line | Es el ID de la línea de pedido del anuncio de reserva renderizado. |
service | Es el nombre del servicio que activó el evento. Se heredó de |
size | Indica el tamaño en píxeles de la creatividad renderizada. |
slot | Es el espacio que activó el evento. Se heredó de |
slot | Indica si el contenido de la ranura cambió con el anuncio renderizado. |
source | Es el ID de la creatividad de la reserva renderizada o del anuncio de reabastecimiento. |
source | Es el ID de la línea de pedido de la reserva renderizada o del anuncio de reabastecimiento. |
yield | Son los IDs de los grupos de rendimiento para el anuncio de reabastecimiento renderizado. |
- Ejemplo
JavaScript
// This listener is called when a slot has finished rendering. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRenderEnded", (event) => { const slot = event.slot; console.group("Slot", slot.getSlotElementId(), "finished rendering."); // Log details of the rendered ad. console.log("Advertiser ID:", event.advertiserId); console.log("Campaign ID:", event.campaignId); console.log("Company IDs:", event.companyIds); console.log("Creative ID:", event.creativeId); console.log("Creative Template ID:", event.creativeTemplateId); console.log("Is backfill?:", event.isBackfill); console.log("Is empty?:", event.isEmpty); console.log("Line Item ID:", event.lineItemId); console.log("Size:", event.size); console.log("Slot content changed?", event.slotContentChanged); console.log("Source Agnostic Creative ID:", event.sourceAgnosticCreativeId); console.log("Source Agnostic Line Item ID:", event.sourceAgnosticLineItemId); console.log("Yield Group IDs:", event.yieldGroupIds); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (heredado)
// This listener is called when a slot has finished rendering. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRenderEnded", function (event) { var slot = event.slot; console.group("Slot", slot.getSlotElementId(), "finished rendering."); // Log details of the rendered ad. console.log("Advertiser ID:", event.advertiserId); console.log("Campaign ID:", event.campaignId); console.log("Company IDs:", event.companyIds); console.log("Creative ID:", event.creativeId); console.log("Creative Template ID:", event.creativeTemplateId); console.log("Is backfill?:", event.isBackfill); console.log("Is empty?:", event.isEmpty); console.log("Line Item ID:", event.lineItemId); console.log("Size:", event.size); console.log("Slot content changed?", event.slotContentChanged); console.log("Source Agnostic Creative ID:", event.sourceAgnosticCreativeId); console.log("Source Agnostic Line Item ID:", event.sourceAgnosticLineItemId); console.log("Yield Group IDs:", event.yieldGroupIds); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called when a slot has finished rendering. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRenderEnded", (event) => { const slot = event.slot; console.group("Slot", slot.getSlotElementId(), "finished rendering."); // Log details of the rendered ad. console.log("Advertiser ID:", event.advertiserId); console.log("Campaign ID:", event.campaignId); console.log("Company IDs:", event.companyIds); console.log("Creative ID:", event.creativeId); console.log("Creative Template ID:", event.creativeTemplateId); console.log("Is backfill?:", event.isBackfill); console.log("Is empty?:", event.isEmpty); console.log("Line Item ID:", event.lineItemId); console.log("Size:", event.size); console.log("Slot content changed?", event.slotContentChanged); console.log("Source Agnostic Creative ID:", event.sourceAgnosticCreativeId); console.log("Source Agnostic Line Item ID:", event.sourceAgnosticLineItemId); console.log("Yield Group IDs:", event.yieldGroupIds); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
- Consulta también
Propiedades
advertiserId
advertiserId: null | number
null
para los espacios vacíos, los anuncios de reabastecimiento y las creatividades renderizadas por servicios distintos de PubAdsService.campaignId
campaignId: null | number
null
para los espacios vacíos, los anuncios de reabastecimiento y las creatividades renderizadas por servicios distintos de PubAdsService.companyIds
companyIds: null | number[]
null
para los espacios vacíos, los anuncios de reserva y las creatividades que renderizan servicios que no son PubAdsService.creativeId
creativeId: null | number
null
para los espacios vacíos, los anuncios de reabastecimiento y las creatividades renderizadas por servicios que no sean PubAdsService.creativeTemplateId
creativeTemplateId: null | number
null
para los espacios vacíos, los anuncios de reabastecimiento y las creatividades renderizadas por servicios distintos de PubAdsService.isBackfill
isBackfill: boolean
true
si el anuncio era de reabastecimiento; de lo contrario, es false
.isEmpty
isEmpty: boolean
true
si no se muestra ningún anuncio, false
en caso contrario.labelIds
labelIds: null | number[]
lineItemId
lineItemId: null | number
null
para los espacios vacíos, los anuncios de reabastecimiento y las creatividades renderizadas por servicios que no sean PubAdsService.size
size: null | string | number[]
[728, 90]
. El valor es null
para los espacios publicitarios vacíos.slotContentChanged
slotContentChanged: boolean
true
si se cambió el contenido, false
de lo contrario.sourceAgnosticCreativeId
sourceAgnosticCreativeId: null | number
null
si el anuncio no es una reserva o un reabastecimiento de líneas de pedido, o si la creatividad se renderiza con servicios distintos de PubAdsService.sourceAgnosticLineItemId
sourceAgnosticLineItemId: null | number
null
si el anuncio no es una reserva o un reabastecimiento de líneas de pedido, o si la creatividad se renderiza con servicios distintos de PubAdsService.yieldGroupIds
yieldGroupIds: null | number[]
null
para los espacios vacíos, los anuncios de reserva y las creatividades renderizadas por servicios que no sean PubAdsService.googletag.events.SlotRequestedEvent
ExtiendePropiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. Se heredó de |
slot | Es el espacio que activó el evento. Se heredó de |
- Ejemplo
JavaScript
// This listener is called when the specified service issues an ad // request for a slot. Each slot will fire this event, even though they // may be batched together in a single request if single request // architecture (SRA) is enabled. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRequested", (event) => { const slot = event.slot; console.log("Slot", slot.getSlotElementId(), "has been requested."); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (heredado)
// This listener is called when the specified service issues an ad // request for a slot. Each slot will fire this event, even though they // may be batched together in a single request if single request // architecture (SRA) is enabled. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRequested", function (event) { var slot = event.slot; console.log("Slot", slot.getSlotElementId(), "has been requested."); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called when the specified service issues an ad // request for a slot. Each slot will fire this event, even though they // may be batched together in a single request if single request // architecture (SRA) is enabled. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRequested", (event) => { const slot = event.slot; console.log("Slot", slot.getSlotElementId(), "has been requested."); if (slot === targetSlot) { // Slot specific logic. } });
- Consulta también
googletag.events.SlotResponseReceived
ExtiendePropiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. Se heredó de |
slot | Es el espacio que activó el evento. Se heredó de |
- Ejemplo
JavaScript
// This listener is called when an ad response has been received // for a slot. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotResponseReceived", (event) => { const slot = event.slot; console.log("Ad response for slot", slot.getSlotElementId(), "received."); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (heredado)
// This listener is called when an ad response has been received // for a slot. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotResponseReceived", function (event) { var slot = event.slot; console.log("Ad response for slot", slot.getSlotElementId(), "received."); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called when an ad response has been received // for a slot. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotResponseReceived", (event) => { const slot = event.slot; console.log("Ad response for slot", slot.getSlotElementId(), "received."); if (slot === targetSlot) { // Slot specific logic. } });
- Consulta también
googletag.events.SlotVisibilityChangedEvent
ExtiendePropiedades | |
---|---|
in | Es el porcentaje del área del anuncio que es visible. |
service | Es el nombre del servicio que activó el evento. Se heredó de |
slot | Es el espacio que activó el evento. Se heredó de |
- Ejemplo
JavaScript
// This listener is called whenever the on-screen percentage of an // ad slot's area changes. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotVisibilityChanged", (event) => { const slot = event.slot; console.group("Visibility of slot", slot.getSlotElementId(), "changed."); // Log details of the event. console.log("Visible area:", `${event.inViewPercentage}%`); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (heredado)
// This listener is called whenever the on-screen percentage of an // ad slot's area changes. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotVisibilityChanged", function (event) { var slot = event.slot; console.group("Visibility of slot", slot.getSlotElementId(), "changed."); // Log details of the event. console.log("Visible area:", "".concat(event.inViewPercentage, "%")); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called whenever the on-screen percentage of an // ad slot's area changes. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotVisibilityChanged", (event) => { const slot = event.slot; console.group("Visibility of slot", slot.getSlotElementId(), "changed."); // Log details of the event. console.log("Visible area:", `${event.inViewPercentage}%`); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
- Consulta también
Propiedades
inViewPercentage
inViewPercentage: number
googletag.secureSignals
Interfaces | |
---|---|
Bidder | Muestra un indicador seguro para un ofertante específico. |
Publisher | Muestra un indicador seguro para un publicador específico. |
Secure | Una interfaz para administrar indicadores seguros. |
Alias de tipo | |
---|---|
Secure | Es una interfaz para mostrar un indicador seguro para un ofertante o proveedor específico. |
Alias de tipo
SecureSignalProvider
SecureSignalProvider: BidderSignalProvider | PublisherSignalProvider
id
o networkCode
, pero no ambos.googletag.secureSignals.BidderSignalProvider
Un proveedor de indicadores seguros del ofertante consta de 2 partes:
- Una función de recopilador, que muestra un
Promise
que se resuelve en un indicador seguro - Un
id
que identifica al ofertante asociado con el indicador.
Propiedades | |
---|---|
collector | Una función que muestra un Promise que se resuelve en un indicador seguro. |
id | Es un identificador único para el recopilador asociado con este indicador seguro, tal como se registra en Google Ad Manager. |
- Ejemplo
JavaScript
// id is provided googletag.secureSignalProviders.push({ id: "collector123", collectorFunction: () => { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
JavaScript (heredado)
// id is provided googletag.secureSignalProviders.push({ id: "collector123", collectorFunction: function () { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
TypeScript
// id is provided googletag.secureSignalProviders!.push({ id: "collector123", collectorFunction: () => { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
- Consulta también
Propiedades
collectorFunction
collectorFunction: (() => Promise<string>)
Promise
que se resuelve en un indicador seguro.id
id: string
googletag.secureSignals.PublisherSignalProvider
Un proveedor de indicadores de publicador consta de 2 partes:
- Una función de recopilador, que muestra un
Promise
que se resuelve en un indicador seguro - Un
networkCode
que identifica al publicador asociado con el indicador.
Propiedades | |
---|---|
collector | Una función que muestra un Promise que se resuelve en un indicador seguro. |
network | El código de red (como se ve en la ruta de la unidad de anuncios) del publicador asociado con este indicador seguro |
- Ejemplo
JavaScript
// networkCode is provided googletag.secureSignalProviders.push({ networkCode: "123456", collectorFunction: () => { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
JavaScript (heredado)
// networkCode is provided googletag.secureSignalProviders.push({ networkCode: "123456", collectorFunction: function () { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
TypeScript
// networkCode is provided googletag.secureSignalProviders!.push({ networkCode: "123456", collectorFunction: () => { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
- Consulta también
Propiedades
collectorFunction
collectorFunction: (() => Promise<string>)
Promise
que se resuelve en un indicador seguro.networkCode
networkCode: string
googletag.secureSignals.SecureSignalProvidersArray
Métodos | |
---|---|
clear | Borra todos los indicadores de todos los recopiladores de la caché. |
push | Agrega un nuevo secureSignals.SecureSignalProvider al array de proveedores de indicadores y comienza el proceso de generación de indicadores. |
Métodos
clearAllCache
clearAllCache(): void
Llamar a este método puede reducir la probabilidad de que se incluyan indicadores en las solicitudes de anuncios para las vistas de página actuales y, posiblemente, posteriores. Debido a esto, solo se debe llamar cuando se producen cambios de estado significativos, como eventos que indican un usuario nuevo (acceso, salida, registro, etc.).
push
push(provider: SecureSignalProvider): void
Parámetros | |
---|---|
provider: SecureSignalProvider | Es el objeto secureSignals.SecureSignalProvider que se agregará al array. |