En esta referencia, se 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 |
Es 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 un tipo complejo (unión). |
[number, string] |
Es 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 |
Es 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 y sin 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
Los 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 de los dos puntos puede aceptar o devolver. En la siguiente tabla, se muestran ejemplos de las anotaciones de tipo que puedes ver en esta referencia.
Anotación de tipo | |
---|---|
param: string |
Indica que param acepta o devuelve 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 los parámetros y las propiedades.
|
...params: Array<() => void> |
Indica que params es un
parámetro de resto
que acepta funciones. Los parámetros de resto aceptan una cantidad ilimitada de valores del tipo especificado.
|
googletag
Espacios de nombres | |
---|---|
config | Es la interfaz de configuración principal para los parámetros de configuración a nivel de la página. |
enums | Este es el espacio de nombres que GPT usa para los tipos de enumeración. |
events | Este es el espacio de nombres que GPT usa para los eventos. |
secure | Este es el espacio de nombres que usa GPT para administrar indicadores seguros. |
Interfaces | |
---|---|
Command | El array de comandos acepta una secuencia de funciones y las invoca en orden. |
Companion | Servicio de anuncios complementarios |
Privacy | Es el objeto de configuración para la configuración de privacidad. |
Pub | Servicio de Anuncios para publicadores. |
Response | Es un objeto que representa una sola respuesta del anuncio. |
Rewarded | Objeto que representa la recompensa asociada con un anuncio recompensado. |
Service | 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ños. |
Slot | Slot 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 de uno o varios tamaños. |
Multi | Es una lista de tamaños válidos únicos. |
Named | Son los tamaños con nombre que puede tener una ranura. |
Single | Es un solo tamaño válido para un espacio. |
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ños. |
Variables | |
---|---|
api | Es una marca que indica que la API de GPT se cargó y está lista para llamarse. |
cmd | Es una referencia a la cola de comandos global para la ejecución asíncrona de llamadas relacionadas con GPT. |
pubads | Es una 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 | Devuelve 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 una unidad de anuncios con una ruta y un tamaño determinados, y la asocia con el ID de un elemento div en la página que contendrá el anuncio. |
destroy | Destruye los segmentos proporcionados y quita todos los objetos y las referencias relacionados de esos segmentos de GPT. |
disable | Inhabilita la Consola para publicadores de Google. |
display | Indica a los servicios de ranuras que rendericen la ranura. |
enable | Habilita todos los servicios de GPT que se definieron para los espacios publicitarios de la página. |
get | Obtiene las opciones de configuración generales para el conjunto de páginas establecido por setConfig. |
get | Devuelve la versión actual de GPT. |
open | Abre la Consola para publicadores de Google. |
pubads | Devuelve una referencia a PubAdsService. |
set | Establece el título para todos los elementos iframe del contenedor de anuncios creados por PubAdsService, a partir de este punto. |
set | Establece opciones de configuración generales para 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 elemento div principal y, luego, cambia el tamaño de su altura para que se ajuste al contenido de la creatividad. Se comporta de manera similar a 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 de declarar el tamaño de una ranura 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 asincronía es usar googletag.cmd para poner en cola las devoluciones de llamada para cuando GPT esté listo. No es necesario que estas devoluciones de llamada verifiquen 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 variable
googletag.cmd
se inicializa en un array de JavaScript vacío con la sintaxis de la etiqueta de GPT en la página, 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, se revisa el array y se ejecutan 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 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 de generación de indicadores y las invoca en orden. Está diseñado para reemplazar un array estándar que se usa para poner en cola funciones de generación de indicadores que se invocarán una vez que se cargue 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 | 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 las creatividades fuera de página para obtener más detalles.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 unidad de anuncios completa con el código de red y el código de unidad de anuncios. |
| Es el ID de la división que contendrá esta unidad de anuncios o este OutOfPageFormat. |
Muestra | |
---|---|
Slot | null | Es la ranura recién creada o null si no se puede crear una ranura. |
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 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 responsiva o si el tamaño del viewport es más pequeño que el tamaño más pequeño proporcionado en la asignación. |
| ID del div que contendrá esta unidad de anuncios. |
Muestra | |
---|---|
Slot | null | Es la ranura recién creada o null si no se puede crear una ranura. |
destroySlots
destroySlots(slots?: Slot[]): boolean
Si se llama a esta API en un espacio, se borra el anuncio y se quita el objeto del espacio del estado interno que mantiene GPT. Llamar a más funciones en el objeto de ranura generará un comportamiento indefinido. Ten en cuenta que es posible que el navegador no libere la memoria asociada a ese espacio si la página del publicador mantiene una referencia a él. Llamar a esta API hace que el div asociado a ese espacio esté 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, por lo que las solicitudes futuras no se verán afectadas por bloqueos de ruta ni exclusiones de la competencia que involucren a este anuncio. Si no se llama a esta función antes de quitar el div de una ranura 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 espacios vacíos que se destruirán. El array es opcional; si no se especifica, se destruirán todos los espacios. |
Muestra | |
---|---|
boolean | true si se destruyeron ranuras, false en caso contrario. |
disablePublisherConsole
disablePublisherConsole(): void
- Consulta también
pantalla
display(divOrSlot: string | Element | Slot): void
Si se utiliza la arquitectura de solicitud única (SRA), todos los espacios publicitarios no recuperados en el momento en que se llama a este método se recuperarán de una sola vez. Para forzar que no se muestre un espacio publicitario, se debe quitar todo el elemento div.
- Consulta también
Parámetros | |
---|---|
divOrSlot: string | Element | Slot | Es el ID del elemento div que contiene el espacio publicitario, el elemento div o el objeto de espacio. Si se proporciona un elemento div, debe tener un atributo "id" que coincida con el ID que se pasó a defineSlot. |
enableServices
enableServices(): void
getConfig
getConfig(keys: string | string[]): Pick<PageSettingsConfig, "adsenseAttributes" | "disableInitialLoad" | "targeting">
Este método no admite todas las propiedades de
setConfig()
. Las propiedades admitidas son las siguientes:- Ejemplo
JavaScript
// Get the value of the `targeting` setting. const targetingConfig = googletag.getConfig("targeting"); // Get the value of the `adsenseAttributes` and `disableInitialLoad` settings. const config = googletag.getConfig(["adsenseAttributes", "disableInitialLoad"]);
JavaScript (heredado)
// Get the value of the `targeting` setting. var targetingConfig = googletag.getConfig("targeting"); // Get the value of the `adsenseAttributes` and `disableInitialLoad` settings. var config = googletag.getConfig(["adsenseAttributes", "disableInitialLoad"]);
TypeScript
// Get the value of the `targeting` setting. const targetingConfig = googletag.getConfig("targeting"); // Get the value of the `adsenseAttributes` and `disableInitialLoad` settings. const config = googletag.getConfig(["adsenseAttributes", "disableInitialLoad"]);
Parámetros | |
---|---|
keys: string | string[] | Son las claves de las opciones de configuración que se obtendrán. |
Muestra | |
---|---|
Pick<PageSettingsConfig, "adsenseAttributes" | "disableInitialLoad" | "targeting"> | Son las opciones de configuración de la ranura. |
getVersion
getVersion(): string
- Consulta también
Muestra | |
---|---|
string | Es la cadena de versión de GPT que se está ejecutando actualmente. |
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 | |
---|---|
| Es el ID de un elemento div de espacio publicitario. Este valor es opcional. Cuando se proporcione, la Consola para publicadores intentará abrirse con los detalles del espacio publicitario especificado a la vista. |
pubads
pubads(): PubAdsService
Muestra | |
---|---|
PubAdsService | Es el servicio de Publisher Ads. |
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 título nuevo para todos los elementos iframe 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 en el tiempo de ejecución siempre será globalThis . Considera pasar una función de flecha para conservar el valor de this del contexto léxico circundante. |
Muestra | |
---|---|
number | Es la cantidad de comandos procesados hasta el momento. Esto es compatible con el valor de retorno de 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. Heredado de |
get | Obtén la lista de ranuras asociadas a este servicio. Heredado de |
remove | Quita un objeto de escucha registrado anteriormente. Heredado 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 publicitarios que también estén registrados en PubAdsService. Debido a las restricciones de políticas, este método no está diseñado para completar 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 completar automáticamente los espacios vacíos, false para dejarlos sin cambios |
googletag.PrivacySettingsConfig
Propiedades | |
---|---|
child | Indica si la página se debe tratar como contenido dirigido a niños. |
limited | Habilita la publicación para que se ejecute en el modo de anuncios limitados y, así, satisfacer las necesidades de cumplimiento de las reglamentaciones de los publicadores. |
non | Permite que la publicación se ejecute en el modo de anuncios no personalizados para ayudar a satisfacer las necesidades de cumplimiento reglamentario de los publicadores. |
restrict | Permite que la publicación se ejecute en el modo de procesamiento restringido para ayudar a los publicadores a cumplir con los requisitos reglamentarios. |
traffic | Indica si las solicitudes representan tráfico comprado o tráfico orgánico. |
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?: boolean
null
para borrar la configuración.Optional
limitedAds
limitedAds?: boolean
Puedes indicarle a GPT que solicite anuncios limitados de dos maneras:
- Automáticamente, a través de un indicador de una plataforma de administración de consentimiento del MTC v2.0 de IAB
- De forma manual, estableciendo 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?: 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 de GPT específico en la página. Heredado de |
clear | Quita los anuncios de los espacios determinados y los reemplaza por contenido en blanco. |
clear | Obsoleto. Borra todas las etiquetas de exclusión de categorías de anuncios a nivel de la página. |
clear | Obsoleto. Borra los parámetros de segmentación personalizados para una clave específica o para todas las claves. |
collapse | Obsoleto. Habilita la contracción de los elementos div de espacios para que no ocupen espacio en la página cuando no haya contenido del anuncio para mostrar. |
disable | Obsoleto. 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 publicitario con la ruta de acceso y el tamaño de la unidad de anuncios proporcionados. |
enable | Obsoleto. Habilita la carga diferida en GPT según lo define el objeto de configuración. |
enable | Obsoleto. Habilita el modo de solicitud única para recuperar varios anuncios al mismo tiempo. |
enable | Obsoleto. Indica a GPT que habrá anuncios de video en la página. |
get | Obsoleto. Devuelve el valor del atributo de AdSense asociado con la clave determinada. |
get | Obsoleto. Devuelve las claves de atributo que se configuraron en este servicio. |
get | Obtén la lista de ranuras asociadas a este servicio. Heredado de |
get | Obsoleto. Devuelve un parámetro de segmentación personalizado específico a nivel del servicio que se configuró. |
get | Obsoleto. Devuelve la lista de todas las claves de segmentación personalizadas a nivel del servicio que se configuraron. |
is | Obsoleto. Devuelve un valor que indica si se inhabilitaron correctamente las solicitudes iniciales de anuncios con una llamada anterior a PubAdsService.disableInitialLoad. |
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. Heredado de |
set | Obsoleto. Establece valores para los atributos de AdSense que se aplican a todos los espacios publicitarios del servicio Publisher Ads. |
set | Obsoleto. Establece una exclusión de categoría de anuncio a nivel de la página para el nombre de etiqueta determinado. |
set | Obsoleto. Habilita o inhabilita el centrado horizontal de los anuncios. |
set | Obsoleto. Configura si se debe forzar la renderización de todos los anuncios de la página con un contenedor de SafeFrame. |
set | Obsoleto. Pasa información de ubicación de los sitios web para que puedas segmentar geográficamente las líneas de pedido hacia 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 | Obsoleto. Establece las preferencias a nivel de la página para la configuración de SafeFrame. |
set | Obsoleto. Establece parámetros de segmentación personalizados para una clave determinada que se aplican a todos los espacios publicitarios del servicio de Publisher Ads. |
set | Obsoleto. 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 correlacionador que se envía con las solicitudes de anuncios, lo que inicia una nueva vista de página. |
Métodos
borrar
clear(slots?: Slot[]): boolean
En particular, borrar una ranura quita el anuncio de la vista de página de larga duración de GPT, por lo que las solicitudes futuras no se verán afectadas por bloqueos 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 | Devuelve true si se borraron los segmentos, y 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 | Es el objeto de servicio en el 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 | |
---|---|
| Es la 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 | Es el objeto de servicio en el 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 contraer la división y false si es imposible habilitar el modo de contraer porque se llamó al método después de que se habilitó el servicio. |
disableInitialLoad
disableInitialLoad(): void
refresh
.pantalla
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 de la ranura y 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 de la ranura o 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 forzada de SafeFrame, etcétera) solo se aplicará a las solicitudes posteriores de
display()
o refresh()
.- 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");
Parámetros | |
---|---|
adUnitPath: string | Es la ruta de acceso a la unidad de anuncios del espacio que se renderizará. |
size: GeneralSize | Ancho y altura de la ranura. |
| Es el ID de la división que contiene el espacio o el elemento de división en sí. |
| 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 la 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 de carga diferida. Las configuraciones omitidas usarán un conjunto 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 habilitar el modo de solicitud única porque se llamó al método después de que se habilitó el servicio. |
enableVideoAds
enableVideoAds(): void
get
get(key: string): 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 | Nombre del atributo que se buscará. |
Muestra | |
---|---|
string | Valor actual de la clave del 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[] | Son los valores asociados con esta clave o un array vacío si no existe 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 | Devuelve true si una llamada anterior a PubAdsService.disableInitialLoad se realizó correctamente; de lo contrario, devuelve false . |
refresh
refresh(slots?: Slot[], options?: {
changeCorrelator: boolean;
}): void
Para que funcione correctamente en todos los navegadores, la llamada a
refresh
debe estar precedida por una llamada a display
la ranura del anuncio. 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.Cuando se actualiza un espacio, se quita el anuncio anterior de la vista de página de larga duración de GPT, por lo que las solicitudes futuras no se verán afectadas por los bloqueos ni las exclusiones de la competencia que involucren a 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 | |
---|---|
| Son las ranuras 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 a esta llamada de actualización.
|
set
set(key: string, value: string): PubAdsService
Si se llama a este método más de una vez para la misma clave, se anularán los valores establecidos previamente 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 | Es el objeto de servicio en el 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 | Es la etiqueta de exclusión de categorías de anuncios que se agregará. |
Muestra | |
---|---|
PubAdsService | Es el objeto de servicio en el que se llamó al método. |
setCentering
setCentering(centerAds: boolean): void
Se debe invocar este método 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 y 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 subsiguientes que se realicen para los espacios respectivos.
- Si se especifica, el parámetro de configuración a nivel del espacio siempre anulará el parámetro de configuración a nivel de la página.
- Si se configura como
true
(a nivel del espacio o de la página), el anuncio siempre se renderizará con un contenedor de SafeFrame, independientemente de la elección que se realice 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 realizada 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 elementos iframe o que dependen de que se rendericen directamente en la página de un 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 falso. Si configuras este parámetro como false cuando no se especificó antes, no cambiará nada. |
Muestra | |
---|---|
PubAdsService | Es el objeto de servicio en el que se llamó al método. |
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 | Es el objeto de servicio en el 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 privacidad. |
Muestra | |
---|---|
PubAdsService | Es el objeto de servicio en el 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 proporcionado por el publicador. Debe tener entre 32 y 150 caracteres. |
Muestra | |
---|---|
PubAdsService | Es el objeto de servicio en el que se llamó al método. |
setSafeFrameConfig
setSafeFrameConfig(config: SafeFrameConfig): PubAdsService
Estas preferencias a nivel de la página se anularán con las preferencias a nivel del espacio, si se especifican.
- 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 | Es el objeto de configuración. |
Muestra | |
---|---|
PubAdsService | Es el objeto de servicio en el 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 | Es la clave del parámetro de segmentación. |
value: string | string[] | Es el valor del parámetro de segmentación o un array de valores. |
Muestra | |
---|---|
PubAdsService | Es el objeto de servicio en el 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 | Es el ID de contenido del video. |
videoCmsId: string | Es el ID del CMS de video. |
updateCorrelator
updateCorrelator(): PubAdsService
Nota: Esto no afecta 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 | Es el objeto de servicio en el 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 del concepto. |
- Consulta también
Propiedades
advertiserId
advertiserId: number
campaignId
campaignId: number
creativeId
creativeId: number
creativeTemplateId
creativeTemplateId: number
lineItemId
lineItemId: 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, "moneda"). |
- Consulta también
Propiedades
amount
amount: number
type
type: string
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 de GPT específico en la página. |
get | Obtén la lista de ranuras asociadas a 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 generado por GPT. Los tipos de eventos distinguen mayúsculas de minúsculas. |
listener: ((arg: EventTypeMap[K]) => void) | Función que toma un solo argumento de objeto de evento. |
Muestra | |
---|---|
Service | Es el objeto de servicio en el 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 generado por GPT. Los tipos de eventos distinguen mayúsculas de minúsculas. |
listener: ((event: EventTypeMap[K]) => void) | 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 uno o varios tamaños que representa el espacio. |
build | Compila una especificación de mapa de tamaños a partir de las asignaciones agregadas 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 | Son los tamaños de la ranura para esta entrada de asignación. |
Muestra | |
---|---|
SizeMappingBuilder | Es una referencia a este compilador. |
build
build(): SizeMappingArray
Si se proporcionaron asignaciones no válidas, este método devolverá
null
. De lo contrario, devuelve 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 | |
---|---|
SizeMappingArray | Es 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 Service a este segmento. |
clear | Obsoleto. Borra todas las etiquetas de exclusión de categorías de anuncios a nivel del espacio para este espacio. |
clear | Obsoleto. Borra parámetros de segmentación personalizados específicos o todos los parámetros de segmentación personalizados a nivel de la posición para esta posición. |
define | Establece un array de asignaciones desde un tamaño mínimo del viewport hasta el tamaño de la ranura para esta ranura. |
get | Obsoleto. Devuelve el valor del atributo de AdSense asociado a la clave determinada para este espacio. |
get | Devuelve 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 | Obsoleto. Devuelve la lista de claves de atributos establecidas en este segmento. |
get | Obsoleto. Devuelve las etiquetas de exclusión de categorías de anuncios para este espacio. |
get | Obtiene las opciones de configuración generales del espacio publicitario establecidas por setConfig. |
get | Devuelve la información de la respuesta del anuncio. |
get | Devuelve el ID de la ranura div proporcionado cuando se definió la ranura. |
get | Obsoleto. Devuelve un parámetro de segmentación personalizada específico establecido en este espacio. |
get | Obsoleto. Devuelve la lista de todas las claves de segmentación personalizadas establecidas en este espacio. |
set | Obsoleto. Establece un valor para un atributo de AdSense en este espacio publicitario. |
set | Obsoleto. Establece una etiqueta de exclusión de categoría de anuncio a nivel del espacio en este espacio. |
set | Obsoleto. Establece la URL de clic a la que se redireccionará a los usuarios después de que hagan clic en el anuncio. |
set | Obsoleto. Establece si se debe ocultar el espacio div cuando no hay un anuncio en él. |
set | Establece opciones de configuración generales para este segmento. |
set | Obsoleto. Configura si se debe forzar la renderización de los anuncios en este espacio publicitario con un contenedor de SafeFrame. |
set | Obsoleto. Establece las preferencias a nivel de la ranura para la configuración de SafeFrame. |
set | Obsoleto. Establece un parámetro de segmentación personalizado para este espacio. |
update | Obsoleto. Establece parámetros de segmentación personalizados para este espacio, a partir de un mapa de 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 | Es el objeto de ranura en el 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 | Es el objeto de ranura en el 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 | |
---|---|
| Es la 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 | Es el objeto de ranura en el 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 | Es un 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 | Es el objeto de ranura en el que se llamó al método. |
get
get(key: string): 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 | Nombre del atributo que se buscará. |
Muestra | |
---|---|
string | Valor actual de la clave del 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 | Es la 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[] | Son las etiquetas de exclusión de categorías de anuncios para este espacio o un array vacío si no se configuró ninguna. |
getConfig
getConfig(keys: string | string[]): Pick<SlotSettingsConfig, "adsenseAttributes" | "targeting" | "categoryExclusion">
Este método no admite todas las propiedades de
setConfig()
. Las propiedades admitidas son las siguientes:- Ejemplo
JavaScript
const slot = googletag.defineSlot("/1234567/sports", [160, 600], "div"); // Get the value of the `targeting` setting. const targetingConfig = slot.getConfig("targeting"); // Get the value of the `adsenseAttributes` and `categoryExclusion` settings. const config = slot.getConfig(["adsenseAttributes", "categoryExclusion"]);
JavaScript (heredado)
var slot = googletag.defineSlot("/1234567/sports", [160, 600], "div"); // Get the value of the `targeting` setting. var targetingConfig = slot.getConfig("targeting"); // Get the value of the `adsenseAttributes` and `categoryExclusion` settings. var config = slot.getConfig(["adsenseAttributes", "categoryExclusion"]);
TypeScript
const slot = googletag.defineSlot("/1234567/sports", [160, 600], "div")!; // Get the value of the `targeting` setting. const targetingConfig = slot.getConfig("targeting"); // Get the value of the `adsenseAttributes` and `categoryExclusion` settings. const config = slot.getConfig(["adsenseAttributes", "categoryExclusion"]);
Parámetros | |
---|---|
keys: string | string[] | Son las claves de las opciones de configuración que se obtendrán. |
Muestra | |
---|---|
Pick<SlotSettingsConfig, "adsenseAttributes" | "targeting" | "categoryExclusion"> | Son las opciones de configuración de la ranura. |
getResponseInformation
getResponseInformation(): ResponseInformation
null
.Muestra | |
---|---|
ResponseInformation | Es la información de respuesta del anuncio más reciente o null si la ranura no tiene un anuncio. |
getSlotElementId
getSlotElementId(): string
div
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 la ranura div |
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[] | Son los valores asociados con esta clave o un array vacío si no existe 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 se llama 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 | Es el objeto de ranura en el 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 | Es la etiqueta de exclusión de categorías de anuncios que se agregará. |
Muestra | |
---|---|
Slot | Es el objeto de ranura en el 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 agrega al valor proporcionado. Las llamadas posteriores sobrescriben el valor. Esto solo funciona para solicitudes que no son 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 establecerá. |
Muestra | |
---|---|
Slot | Es el objeto de ranura en el 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 contraerá el espacio incluso antes de que se recupere un anuncio. Se ignora si el parámetro de contracción no es true . |
Muestra | |
---|---|
Slot | Es el objeto de ranura en el que se llamó al método. |
setConfig
setConfig(slotConfig: SlotSettingsConfig): void
Parámetros | |
---|---|
slotConfig: SlotSettingsConfig | Es 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 subsiguientes que se realicen para los espacios respectivos.
- Si se especifica, el parámetro de configuración a nivel del espacio siempre anulará el parámetro de configuración a nivel de la página.
- Si se configura como
true
(a nivel del espacio o de la página), el anuncio siempre se renderizará con un contenedor de SafeFrame, independientemente de la elección que se realice 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 realizada 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 elementos iframe o que dependen de que se rendericen directamente en la página de un 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 la renderización de todos los anuncios de este espacio en SafeFrames y false para inhabilitar un parámetro de configuración a nivel de la página (si está presente). Si se establece en false cuando no se especifica a nivel de la página, no se cambiará nada. |
Muestra | |
---|---|
Slot | Es el objeto de ranura en el que se llamó al método. |
setSafeFrameConfig
setSafeFrameConfig(config: SafeFrameConfig): Slot
Estas preferencias a nivel del espacio, si se especifican, 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: SafeFrameConfig | Es el objeto de configuración. |
Muestra | |
---|---|
Slot | Es el objeto de ranura en el 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 | Es la clave del parámetro de segmentación. |
value: string | string[] | Es el valor del parámetro de segmentación o un array de valores. |
Muestra | |
---|---|
Slot | Es el objeto de ranura en el que se llamó al método. |
updateTargetingFromMap
updateTargetingFromMap(map: {
[adUnitPath: string]: string | string[];
}): Slot
Notas:
- En caso de sobrescritura, solo se conservará el último valor.
- Si el valor es un array, se reemplazará cualquier valor anterior, no se combinará.
- Los valores establecidos aquí anulará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 pares clave-valor del parámetro de segmentación. |
Muestra | |
---|---|
Slot | Es el objeto de ranura en el que se llamó al método. |
googletag.config
Interfaces | |
---|---|
Ad | Es la configuración para controlar la expansión de anuncios. |
Ad | Es la configuración para controlar el comportamiento de los anuncios de AdSense. |
Component | Es un objeto que representa una sola subasta de componentes en una subasta de anuncios integrada en el dispositivo. |
Interstitial | Es un objeto que define el comportamiento de un solo espacio publicitario intersticial. |
Lazy | Es la configuración para controlar el uso de la carga diferida en GPT. |
Page | Es la interfaz de configuración principal para los parámetros de configuración a nivel de la página. |
Privacy | Es la configuración para controlar los tratamientos de privacidad de los publicadores. |
Publisher | Es el objeto de configuración de los indicadores proporcionados por el publicador (PPS). |
Safe | Es la configuración para controlar SafeFrame en GPT. |
Slot | Es la interfaz de configuración principal para los parámetros de configuración a nivel de la ranura. |
Taxonomy | Es un objeto que contiene los valores de una sola Taxonomy. |
Video | Es la configuración para establecer la configuración relacionada con los anuncios de video. |
Alias de tipo | |
---|---|
Interstitial | Son las acciones que activan los anuncios intersticiales compatibles. |
Privacy | Son los 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?: boolean
Si se establece este valor, se anula la configuración predeterminada en Google Ad Manager.
googletag.config.AdSenseAttributesConfig
Estos atributos se pueden usar para anular la configuración del servidor por solicitud.
Propiedades | |
---|---|
adsense | Es el formato del anuncio de AdSense. |
adsense | Son los IDs de los canales de AdSense. |
adsense | Indica si el modo de prueba está habilitado o no. |
document | Es el idioma de la página en la que se muestran los anuncios. |
page | Es la URL de la página en la que se muestran los anuncios. |
- Consulta también
Propiedades
Optional
adsense_ad_format
adsense_ad_format?: "120x240_as" | "120x600_as" | "125x125_as" | "160x600_as" | "180x150_as" | "200x200_as" | "234x60_as" | "250x250_as" | "300x250_as" | "336x280_as" | "468x60_as" | "728x90_as"
Optional
adsense_channel_ids
adsense_channel_ids?: string
Los valores permitidos son los IDs de los canales separados por el signo "+".
Ejemplo:
271828183+314159265
Optional
adsense_test_mode
adsense_test_mode?: "on"
Cuando se establece en
on
, los anuncios se marcan como solo para pruebas y no se incluirán en el recuento ni en la facturación. Este parámetro de configuración debe anularse para el tráfico de producción que no sea de prueba.Optional
document_language
document_language?: string
Los valores permitidos son códigos de idioma ISO 639-1 válidos.
Ejemplo:
en
- Consulta también
Optional
page_url
page_url?: string
Los valores permitidos son URLs válidas.
Ejemplo:
http://www.example.com
googletag.config.ComponentAuctionConfig
Propiedades | |
---|---|
auction | Es un objeto de configuración de la subasta para esta subasta de componente. |
config | Es la clave de configuración asociada a esta subasta de componentes. |
Propiedades
auctionConfig
auctionConfig: {
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 configure anulará las configuraciones anteriores.googletag.config.InterstitialConfig
Propiedades | |
---|---|
require | Indica si se requiere consentimiento para el almacenamiento local para mostrar este anuncio intersticial. |
triggers | Es la configuración del activador de intersticial para este anuncio intersticial. |
Propiedades
Optional
requireStorageAccess
requireStorageAccess?: boolean
GPT usa el almacenamiento local para aplicar una limitación de frecuencia a los anuncios intersticiales. Sin embargo, los usuarios que no proporcionaron el consentimiento de almacenamiento local aún son aptos para que se les publiquen anuncios intersticiales. Si se configura esta propiedad como
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?: Partial<Record<InterstitialTrigger, boolean>>
Si se establece el valor de un activador de intersticial en
true
, se habilitará, y si se establece 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.LazyLoadConfig
Propiedades | |
---|---|
fetch | Es la distancia mínima desde el viewport actual a la que debe estar una ranura antes de que solicitemos un anuncio, expresada como un porcentaje del tamaño del viewport. |
mobile | Es un multiplicador que se aplica a los márgenes en dispositivos móviles. |
render | Es la distancia mínima desde el viewport actual a la que debe estar una ranura antes de que rendericemos un anuncio, expresada como un porcentaje del tamaño del viewport. |
- Consulta también
Propiedades
Optional
fetchMarginPercent
fetchMarginPercent?: number
Se usa en conjunto con renderMarginPercent. Este parámetro de configuración permite realizar una recuperación previa de un anuncio, pero espera para renderizar y descargar otros recursos secundarios. Por lo tanto, este valor siempre debe ser mayor o igual que renderMarginPercent.
Un valor de
0
significa "cuando la ranura ingresa al viewport", 100
significa "cuando el anuncio está a 1 viewport de distancia", y así sucesivamente.Optional
mobileScaling
mobileScaling?: number
Esto permite tener diferentes márgenes en dispositivos móviles y computadoras de escritorio, en los que los tamaños del viewport y las velocidades de desplazamiento pueden ser diferentes. Por ejemplo, un valor de 2.0 multiplicará todos los márgenes por 2 en los dispositivos móviles, lo que aumentará la distancia mínima a la que una ranura puede estar del viewport antes de recuperar y renderizar.
Optional
renderMarginPercent
renderMarginPercent?: number
Se usa en conjunto con fetchMarginPercent. Este parámetro de configuración permite realizar una recuperación previa de un anuncio, pero espera para renderizar y descargar otros recursos secundarios. Por lo tanto, este valor siempre debe ser menor o igual que fetchMarginPercent.
Un valor de
0
significa "cuando la ranura ingresa al viewport", 100
significa "cuando el anuncio está a 1 viewport de distancia", y así sucesivamente.googletag.config.PageSettingsConfig
Permite establecer varios parámetros 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 ver el conjunto de funciones, consulta los campos dentro del tipo PageSettingsConfig a continuación.
Ejemplos:
- Solo se modifican las funciones especificadas en la llamada a 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 | Es la configuración para controlar la expansión de anuncios. |
adsense | Es un parámetro de configuración para establecer atributos de AdSense. |
ad | Obsoleto. |
category | Es un parámetro de configuración para establecer exclusiones de categorías de anuncios. |
centering | Es un parámetro de configuración para controlar el centrado horizontal de los anuncios. |
collapse | Es un parámetro de configuración para controlar el comportamiento de contracción de los espacios publicitarios. |
disable | Es un parámetro de configuración para controlar cuándo se solicitan los anuncios. |
lazy | Es la configuración para controlar el uso de la carga diferida en GPT. |
location | Es el parámetro de configuración para segmentar geográficamente las líneas de pedido según ubicaciones geográficas. |
pps | Es la configuración para controlar los indicadores proporcionados por el publicador (PPS). |
privacy | Es la configuración para controlar los tratamientos de privacidad de los publicadores. |
safe | Es la configuración para controlar el uso de SafeFrame en GPT. |
single | Es un parámetro de configuración para habilitar o inhabilitar la arquitectura de solicitud única (SRA). |
targeting | Es un parámetro de configuración para controlar la segmentación por pares clave-valor. |
thread | Es un parámetro de configuración para controlar si GPT debe ceder el subproceso de JS cuando solicita y renderiza creatividades. |
video | Es la configuración para controlar los anuncios de video. |
Propiedades
Optional
adExpansion
adExpansion?: AdExpansionConfig
Optional
adsenseAttributes
adsenseAttributes?: AdSenseAttributesConfig
Los atributos de AdSense configurados a través de este parámetro se aplicarán a todos los espacios publicitarios de la página. Se puede llamar a este parámetro de configuración varias veces para definir varios valores de atributos o anular los valores existentes.
Los cambios en los atributos de AdSense solo se aplican a los anuncios solicitados después de que se haya llamado a este método. Por ese motivo, se recomienda llamar a este método antes de cualquier llamada a googletag.display o PubAdsService.refresh.
- Ejemplo
JavaScript
// Set the document language and page URL. googletag.setConfig({ adsenseAttributes: { document_language: "en", page_url: "http://www.example.com" }, }); // Clear the page URL only. googletag.setConfig({ adsenseAttributes: { page_url: null } }); // Clear all AdSense attributes. googletag.setConfig({ adsenseAttributes: null });
JavaScript (heredado)
// Set the document language and page URL. googletag.setConfig({ adsenseAttributes: { document_language: "en", page_url: "http://www.example.com" }, }); // Clear the page URL only. googletag.setConfig({ adsenseAttributes: { page_url: null } }); // Clear all AdSense attributes. googletag.setConfig({ adsenseAttributes: null });
TypeScript
// Set the document language and page URL. googletag.setConfig({ adsenseAttributes: { document_language: "en", page_url: "http://www.example.com" }, }); // Clear the page URL only. googletag.setConfig({ adsenseAttributes: { page_url: null } }); // Clear all AdSense attributes. googletag.setConfig({ adsenseAttributes: null });
Optional
adYield
adYield?: "DISABLED" | "ENABLED_ALL_SLOTS"
Optional
categoryExclusion
categoryExclusion?: string[]
- Ejemplo
JavaScript
// Label = AirlineAd. googletag.setConfig({ categoryExclusion: ["AirlineAd"] }); // Clearing category exclusion setting. googletag.setConfig({ categoryExclusion: null });
JavaScript (heredado)
// Label = AirlineAd. googletag.setConfig({ categoryExclusion: ["AirlineAd"] }); // Clearing category exclusion setting. googletag.setConfig({ categoryExclusion: null });
TypeScript
// Label = AirlineAd. googletag.setConfig({ categoryExclusion: ["AirlineAd"] }); // Clearing category exclusion setting. googletag.setConfig({ categoryExclusion: null });
- Consulta también
Optional
centrado
centering?: boolean
Los cambios en el centrado horizontal solo se aplican a los anuncios solicitados después de que se llama a este método. Por ese motivo, se recomienda llamar a este método antes de cualquier llamada a googletag.display o PubAdsService.refresh.
- Ejemplo
JavaScript
// Make ads centered. googletag.setConfig({ centering: true }); // Clear the centering setting. googletag.setConfig({ centering: null });
JavaScript (heredado)
// Make ads centered. googletag.setConfig({ centering: true }); // Clear the centering setting. googletag.setConfig({ centering: null });
TypeScript
// Make ads centered. googletag.setConfig({ centering: true }); // Clear the centering setting. googletag.setConfig({ centering: null });
Optional
collapseDiv
collapseDiv?: "DISABLED" | "BEFORE_FETCH" | "ON_NO_FILL"
Un espacio publicitario contraído no ocupa ningún espacio en la página.
Valores admitidos:
null
(predeterminado): La ranura no se contraerá.DISABLED
: El espacio no se contraerá, ya sea que se muestre un anuncio o no.BEFORE_FETCH
: La ranura comenzará contraída y se expandirá cuando se muestre un anuncio.ON_NO_FILL
: La ranura comenzará expandida y se contraerá si no se muestra ningún anuncio.
- Ejemplo
JavaScript
// Collapse the div for this slot if no ad is returned. googletag.setConfig({ collapseDiv: "ON_NO_FILL" }); // Collapse the div for this slot by default, and expand only // if an ad is returned. googletag.setConfig({ collapseDiv: "BEFORE_FETCH" }); // Do not collapse the div for this slot. googletag.setConfig({ collapseDiv: "DISABLED" }); // Clear the collapse setting. googletag.setConfig({ collapseDiv: null });
JavaScript (heredado)
// Collapse the div for this slot if no ad is returned. googletag.setConfig({ collapseDiv: "ON_NO_FILL" }); // Collapse the div for this slot by default, and expand only // if an ad is returned. googletag.setConfig({ collapseDiv: "BEFORE_FETCH" }); // Do not collapse the div for this slot. googletag.setConfig({ collapseDiv: "DISABLED" }); // Clear the collapse setting. googletag.setConfig({ collapseDiv: null });
TypeScript
// Collapse the div for this slot if no ad is returned. googletag.setConfig({ collapseDiv: "ON_NO_FILL" }); // Collapse the div for this slot by default, and expand only // if an ad is returned. googletag.setConfig({ collapseDiv: "BEFORE_FETCH" }); // Do not collapse the div for this slot. googletag.setConfig({ collapseDiv: "DISABLED" }); // Clear the collapse setting. googletag.setConfig({ collapseDiv: null });
Optional
disableInitialLoad
disableInitialLoad?: boolean
De forma predeterminada, el método googletag.display registra los espacios publicitarios y solicita anuncios para ellos. Sin embargo, en ocasiones, puede ser preferible separar estas acciones para controlar con mayor precisión cuándo se carga el contenido del anuncio.
Si habilitas este parámetro de configuración, no se solicitarán anuncios para las posiciones registradas cuando se llame al método
display()
. En cambio, se debe realizar una llamada independiente a PubAdsService.refresh para iniciar una solicitud de anuncio.Este método debe llamarse antes de llamar a googletag.enableServices.
- Ejemplo
JavaScript
// Prevent requesting ads when `display()` is called. googletag.setConfig({ disableInitialLoad: true });
JavaScript (heredado)
// Prevent requesting ads when `display()` is called. googletag.setConfig({ disableInitialLoad: true });
TypeScript
// Prevent requesting ads when `display()` is called. googletag.setConfig({ disableInitialLoad: true });
Optional
lazyLoad
lazyLoad?: LazyLoadConfig
La carga diferida es una técnica para retrasar la solicitud y la renderización de anuncios hasta que se acerquen al viewport del usuario. Para obtener un ejemplo más detallado, consulta el ejemplo de carga diferida.
Nota: Si
singleRequest
está habilitado, la recuperación diferida solo funciona cuando todas las ranuras están fuera del margen de recuperación.Cualquier parámetro de configuración de carga diferida que no se especifique cuando se llame a
setConfig()
usará un valor predeterminado establecido por Google. Estos valores predeterminados se pueden ajustar con el tiempo. Para inhabilitar un parámetro de configuración en particular, establece el valor en null
.- Ejemplo
JavaScript
// Enable lazy loading. googletag.setConfig({ lazyLoad: { // Fetch slots within 5 viewports. fetchMarginPercent: 500, // Render slots within 2 viewports. renderMarginPercent: 200, // Double the above values on mobile. mobileScaling: 2.0, }, }); // Clear fetch margin only. googletag.setConfig({ lazyLoad: { fetchMarginPercent: null }, }); // Clear all lazy loading settings. googletag.setConfig({ lazyLoad: null });
JavaScript (heredado)
// Enable lazy loading. googletag.setConfig({ lazyLoad: { // Fetch slots within 5 viewports. fetchMarginPercent: 500, // Render slots within 2 viewports. renderMarginPercent: 200, // Double the above values on mobile. mobileScaling: 2.0, }, }); // Clear fetch margin only. googletag.setConfig({ lazyLoad: { fetchMarginPercent: null }, }); // Clear all lazy loading settings. googletag.setConfig({ lazyLoad: null });
TypeScript
// Enable lazy loading. googletag.setConfig({ lazyLoad: { // Fetch slots within 5 viewports. fetchMarginPercent: 500, // Render slots within 2 viewports. renderMarginPercent: 200, // Double the above values on mobile. mobileScaling: 2.0, }, }); // Clear fetch margin only. googletag.setConfig({ lazyLoad: { fetchMarginPercent: null }, }); // Clear all lazy loading settings. googletag.setConfig({ lazyLoad: null });
Optional
ubicación
location?: string
- Ejemplo
JavaScript
// Geo-target line items to US postal code 10001. googletag.setConfig({ location: "10001,US" }); // Clear the location setting. googletag.setConfig({ location: null });
JavaScript (heredado)
// Geo-target line items to US postal code 10001. googletag.setConfig({ location: "10001,US" }); // Clear the location setting. googletag.setConfig({ location: null });
TypeScript
// Geo-target line items to US postal code 10001. googletag.setConfig({ location: "10001,US" }); // Clear the location setting. googletag.setConfig({ location: null });
- Consulta también
Optional
pps
Optional
privacyTreatments
privacyTreatments?: PrivacyTreatmentsConfig
Optional
safeFrame
safeFrame?: SafeFrameConfig
Los valores configurados a través de este parámetro de configuración se aplicarán a todos los espacios publicitarios de la página. Los espacios publicitarios individuales pueden anular estos valores a través de SlotSettingsConfig.safeFrame.
- Ejemplo
JavaScript
// Force SafeFrame for all ads on the page. googletag.setConfig({ safeFrame: { forceSafeFrame: true }, }); // Configure SafeFrame to allow overlay expansion. googletag.setConfig({ safeFrame: { allowOverlayExpansion: true }, }); // Clear forceSafeFrame setting. googletag.setConfig({ safeFrame: { forceSafeFrame: null }, }); // Clear all SafeFrame settings. googletag.setConfig({ safeFrame: null });
JavaScript (heredado)
// Force SafeFrame for all ads on the page. googletag.setConfig({ safeFrame: { forceSafeFrame: true }, }); // Configure SafeFrame to allow overlay expansion. googletag.setConfig({ safeFrame: { allowOverlayExpansion: true }, }); // Clear forceSafeFrame setting. googletag.setConfig({ safeFrame: { forceSafeFrame: null }, }); // Clear all SafeFrame settings. googletag.setConfig({ safeFrame: null });
TypeScript
// Force SafeFrame for all ads on the page. googletag.setConfig({ safeFrame: { forceSafeFrame: true }, }); // Configure SafeFrame to allow overlay expansion. googletag.setConfig({ safeFrame: { allowOverlayExpansion: true }, }); // Clear forceSafeFrame setting. googletag.setConfig({ safeFrame: { forceSafeFrame: null }, }); // Clear all SafeFrame settings. googletag.setConfig({ safeFrame: null });
Optional
singleRequest
singleRequest?: boolean
Cuando la SRA está habilitada, todos los espacios publicitarios definidos antes de una llamada a googletag.display o PubAdsService.refresh se agruparán en una sola solicitud de anuncio. Esto proporciona beneficios de rendimiento, pero también es necesario para garantizar que se respeten las publicidades simultáneas y las exclusiones competitivas.
Cuando la SRA está inhabilitada, cada espacio publicitario se solicita de forma individual. Este es el comportamiento predeterminado de GPT.
Se debe llamar a este método antes de llamar a googletag.enableServices.
- Ejemplo
JavaScript
// Enable Single Request Architecture. googletag.setConfig({ singleRequest: true });
JavaScript (heredado)
// Enable Single Request Architecture. googletag.setConfig({ singleRequest: true });
TypeScript
// Enable Single Request Architecture. googletag.setConfig({ singleRequest: true });
Optional
segmentación
targeting?: Record<string, string | string[]>
La segmentación configurada a través de este parámetro se aplicará a todos los espacios publicitarios de la página. Este parámetro de configuración se puede llamar varias veces para definir varios pares clave-valor de segmentación o para anular los valores existentes. Las claves de segmentación se definen en tu cuenta de Google Ad Manager.
- Ejemplo
JavaScript
// Setting a single targeting key-value. googletag.setConfig({ targeting: { interests: "sports" } }); // Setting multiple values for a single targeting key googletag.setConfig({ targeting: { interests: ["sports", "music"] } }); // Setting multiple targeting key-values at once. googletag.setConfig({ targeting: { interests: ["sports", "music"], color: "red" } }); // Clearing a single targeting key. googletag.setConfig({ targeting: { interests: null } });
JavaScript (heredado)
// Setting a single targeting key-value. googletag.setConfig({ targeting: { interests: "sports" } }); // Setting multiple values for a single targeting key googletag.setConfig({ targeting: { interests: ["sports", "music"] } }); // Setting multiple targeting key-values at once. googletag.setConfig({ targeting: { interests: ["sports", "music"], color: "red" } }); // Clearing a single targeting key. googletag.setConfig({ targeting: { interests: null } });
TypeScript
// Setting a single targeting key-value. googletag.setConfig({ targeting: { interests: "sports" } }); // Setting multiple values for a single targeting key googletag.setConfig({ targeting: { interests: ["sports", "music"] } }); // Setting multiple targeting key-values at once. googletag.setConfig({ targeting: { interests: ["sports", "music"], color: "red" } }); // Clearing a single targeting key. googletag.setConfig({ targeting: { interests: null } });
- Consulta también
Optional
threadYield
threadYield?: "DISABLED" | "ENABLED_ALL_SLOTS"
GPT solo cederá el subproceso para los navegadores que admitan las APIs de Scheduler.postTask o Scheduler.yield.
Valores admitidos:
null
(predeterminado): GPT cederá el subproceso de JS para los espacios fuera del viewport.ENABLED_ALL_SLOTS
: GPT cederá el subproceso de JS para todos los espacios, independientemente de si el espacio se encuentra dentro del viewport.DISABLED
: GPT no cederá 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
Optional
videoAds
videoAds?: VideoAdsConfig
- Ejemplo
JavaScript
// Enable video ads and set video content and content source IDs. googletag.setConfig({ videoAds: { enableVideoAds: true, videoContentId: "e1eGlRL7ju8", videoCmsId: "1234567", }, });
JavaScript (heredado)
// Enable video ads and set video content and content source IDs. googletag.setConfig({ videoAds: { enableVideoAds: true, videoContentId: "e1eGlRL7ju8", videoCmsId: "1234567", }, });
TypeScript
// Enable video ads and set video content and content source IDs. googletag.setConfig({ videoAds: { enableVideoAds: true, videoContentId: "e1eGlRL7ju8", videoCmsId: "1234567", }, });
- Consulta también
googletag.config.PrivacyTreatmentsConfig
Propiedades | |
---|---|
treatments | Es un array de tratamientos de privacidad del publicador que se pueden habilitar. |
Propiedades
tratamientos
treatments: "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 | Objeto que contiene asignaciones de Taxonomy o valor nulo para borrar la configuración. |
- 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
taxonomies
taxonomies: Partial<Record<Taxonomy, TaxonomyData>>
googletag.config.SafeFrameConfig
Propiedades | |
---|---|
allow | Indica si SafeFrame debe permitir que el contenido del anuncio se expanda superponiéndose con el contenido de la página. |
allow | Indica si SafeFrame debe permitir que el contenido del anuncio se expanda desplazando el contenido de la página. |
force | Indica si se debe forzar el renderizado de los anuncios con un contenedor de SafeFrame. |
sandbox | Indica si SafeFrame debe usar el atributo sandbox de HTML5 para evitar la navegación de nivel superior sin interacción del usuario. |
use | Obsoleto. Indica 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
forceSafeFrame
forceSafeFrame?: boolean
Optional
zona de pruebas
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?: boolean
null
para borrar el valor almacenado.Nota: Esta función está habilitada de forma predeterminada.
- Consulta también
googletag.config.SlotSettingsConfig
Permite establecer varios parámetros con una sola llamada a la API para una sola ranura.
Todas las propiedades que se indican a continuación son ejemplos y no reflejan las funciones reales que utilizan setConfig. Para el conjunto de funciones, consulta los campos dentro del tipo SlotSettingsConfig a continuación.
Ejemplos:
- Solo se modifican los parámetros especificados en la llamada a 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 | Es la configuración para establecer la expansión de anuncios. |
adsense | Es un parámetro de configuración para establecer atributos de AdSense. |
category | Es un parámetro de configuración para establecer exclusiones de categorías de anuncios. |
click | Es el parámetro de configuración para establecer la URL a la que se redireccionará a los usuarios después de que hagan clic en el anuncio. |
collapse | Es el parámetro de configuración para establecer el comportamiento de contracción del espacio publicitario. |
component | Es un array de subastas de componentes que se incluirán en una subasta de anuncios en el dispositivo. |
interstitial | Es la configuración que establece el comportamiento de la ranura de anuncios intersticiales. |
safe | Es la configuración para establecer el uso de SafeFrame en GPT. |
targeting | Es un parámetro de configuración para establecer la segmentación por clave-valor. |
Propiedades
Optional
adExpansion
adExpansion?: AdExpansionConfig
- Consulta también
Optional
adsenseAttributes
adsenseAttributes?: AdSenseAttributesConfig
Los atributos de AdSense configurados a través de este parámetro de configuración solo se aplicarán al espacio publicitario. Se puede llamar a este parámetro de configuración varias veces para definir varios valores de atributos o anular los valores existentes.
Los cambios en los atributos de AdSense solo se aplican a los anuncios solicitados después de que se haya llamado a este método. Por ese motivo, se recomienda llamar a este método antes de cualquier llamada a googletag.display o PubAdsService.refresh.
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Set the AdSense ad format and channel IDs. slot.setConfig({ adsenseAttributes: { adsense_ad_format: "120x240_as", adsense_channel_ids: "271828183+314159265", }, }); // Clear the AdSense channel IDs only. slot.setConfig({ adsenseAttributes: { adsense_channel_ids: null } }); // Clear all AdSense attributes. slot.setConfig({ adsenseAttributes: null });
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Set the AdSense ad format and channel IDs. slot.setConfig({ adsenseAttributes: { adsense_ad_format: "120x240_as", adsense_channel_ids: "271828183+314159265", }, }); // Clear the AdSense channel IDs only. slot.setConfig({ adsenseAttributes: { adsense_channel_ids: null } }); // Clear all AdSense attributes. slot.setConfig({ adsenseAttributes: null });
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); // Set the AdSense ad format and channel IDs. slot.setConfig({ adsenseAttributes: { adsense_ad_format: "120x240_as", adsense_channel_ids: "271828183+314159265", }, }); // Clear the AdSense channel IDs only. slot.setConfig({ adsenseAttributes: { adsense_channel_ids: null } }); // Clear all AdSense attributes. slot.setConfig({ adsenseAttributes: null });
Optional
categoryExclusion
categoryExclusion?: string[]
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Label = AirlineAd slot.setConfig({ categoryExclusion: ["AirlineAd"], }); // Clearing category exclusion setting. slot.setConfig({ categoryExclusion: null });
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Label = AirlineAd slot.setConfig({ categoryExclusion: ["AirlineAd"], }); // Clearing category exclusion setting. slot.setConfig({ categoryExclusion: null });
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); // Label = AirlineAd slot.setConfig({ categoryExclusion: ["AirlineAd"], }); // Clearing category exclusion setting. slot.setConfig({ categoryExclusion: null });
- Consulta también
Optional
clickUrl
clickUrl?: string
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 agrega al valor proporcionado. Si configuras este valor más de una vez, se reemplazará cualquier valor configurado anteriormente. Si pasas
null
, se borrará el valor.Nota: Este parámetro de configuración solo se aplica a las solicitudes que no son de SRA.
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Sets the click URL to 'http://www.example.com?original_click_url='. slot.setConfig({ clickUrl: "http://www.example.com?original_click_url=", }); // Clears the click URL. slot.setConfig({ clickUrl: null, });
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Sets the click URL to 'http://www.example.com?original_click_url='. slot.setConfig({ clickUrl: "http://www.example.com?original_click_url=", }); // Clears the click URL. slot.setConfig({ clickUrl: null, });
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); // Sets the click URL to 'http://www.example.com?original_click_url='. slot.setConfig({ clickUrl: "http://www.example.com?original_click_url=", }); // Clears the click URL. slot.setConfig({ clickUrl: null, });
Optional
collapseDiv
collapseDiv?: "DISABLED" | "BEFORE_FETCH" | "ON_NO_FILL"
Un espacio publicitario contraído no ocupa ningún espacio en la página.
Valores admitidos:
null
(predeterminado): La ranura no se contraerá.DISABLED
: El espacio no se contraerá, ya sea que se muestre un anuncio o no.BEFORE_FETCH
: La ranura comenzará contraída y se expandirá cuando se muestre un anuncio.ON_NO_FILL
: La ranura comenzará expandida y se contraerá si no se muestra ningún anuncio.
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Collapse the div for this slot if no ad is returned. slot.setConfig({ collapseDiv: "ON_NO_FILL", }); // Collapse the div for this slot by default, and expand only // if an ad is returned. slot.setConfig({ collapseDiv: "BEFORE_FETCH", }); // Do not collapse the div for this slot. slot.setConfig({ collapseDiv: "DISABLED", }); // Clear the collapse setting. slot.setConfig({ collapseDiv: null, });
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Collapse the div for this slot if no ad is returned. slot.setConfig({ collapseDiv: "ON_NO_FILL", }); // Collapse the div for this slot by default, and expand only // if an ad is returned. slot.setConfig({ collapseDiv: "BEFORE_FETCH", }); // Do not collapse the div for this slot. slot.setConfig({ collapseDiv: "DISABLED", }); // Clear the collapse setting. slot.setConfig({ collapseDiv: null, });
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); // Collapse the div for this slot if no ad is returned. slot.setConfig({ collapseDiv: "ON_NO_FILL", }); // Collapse the div for this slot by default, and expand only // if an ad is returned. slot.setConfig({ collapseDiv: "BEFORE_FETCH", }); // Do not collapse the div for this slot. slot.setConfig({ collapseDiv: "DISABLED", }); // Clear the collapse setting. slot.setConfig({ collapseDiv: null, });
Optional
componentAuction
componentAuction?: ComponentAuctionConfig[]
Optional
interstitial
interstitial?: InterstitialConfig
- Consulta también
Optional
safeFrame
safeFrame?: SafeFrameConfig
Los valores configurados a través de este parámetro de configuración solo se aplicarán al espacio publicitario y anularán los valores establecidos a través de PageSettingsConfig.safeFrame.
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Force SafeFrame for the slot. slot.setConfig({ safeFrame: { forceSafeFrame: true }, }); // Configure SafeFrame to allow overlay expansion for the slot. slot.setConfig({ safeFrame: { allowOverlayExpansion: true }, }); // Clear forceSafeFrame setting for the slot. slot.setConfig({ safeFrame: { forceSafeFrame: null }, }); // Clear all SafeFrame settings for the slot. slot.setConfig({ safeFrame: null });
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Force SafeFrame for the slot. slot.setConfig({ safeFrame: { forceSafeFrame: true }, }); // Configure SafeFrame to allow overlay expansion for the slot. slot.setConfig({ safeFrame: { allowOverlayExpansion: true }, }); // Clear forceSafeFrame setting for the slot. slot.setConfig({ safeFrame: { forceSafeFrame: null }, }); // Clear all SafeFrame settings for the slot. slot.setConfig({ safeFrame: null });
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); // Force SafeFrame for the slot. slot.setConfig({ safeFrame: { forceSafeFrame: true }, }); // Configure SafeFrame to allow overlay expansion for the slot. slot.setConfig({ safeFrame: { allowOverlayExpansion: true }, }); // Clear forceSafeFrame setting for the slot. slot.setConfig({ safeFrame: { forceSafeFrame: null }, }); // Clear all SafeFrame settings for the slot. slot.setConfig({ safeFrame: null });
Optional
segmentación
targeting?: Record<string, string | string[]>
La segmentación configurada a través de este parámetro de configuración solo se aplicará al espacio publicitario. Este parámetro de configuración se puede llamar varias veces para definir varios pares clave-valor de segmentación o para anular los valores existentes. Las claves de segmentación se definen en tu cuenta de Google Ad Manager.
- Ejemplo
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Setting a single targeting key-value. slot.setConfig({ targeting: { interests: "sports" } }); // Setting multiple values for a single targeting key. slot.setConfig({ targeting: { interests: ["sports", "music"] } }); // Setting multiple targeting key-values at once. slot.setConfig({ targeting: { interests: ["sports", "music"], color: "red" } }); // Clearing a single targeting key. slot.setConfig({ targeting: { interests: null } }); // Clear all targeting keys. slot.setConfig({ targeting: null });
JavaScript (heredado)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); // Setting a single targeting key-value. slot.setConfig({ targeting: { interests: "sports" } }); // Setting multiple values for a single targeting key. slot.setConfig({ targeting: { interests: ["sports", "music"] } }); // Setting multiple targeting key-values at once. slot.setConfig({ targeting: { interests: ["sports", "music"], color: "red" } }); // Clearing a single targeting key. slot.setConfig({ targeting: { interests: null } }); // Clear all targeting keys. slot.setConfig({ targeting: null });
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); // Setting a single targeting key-value. slot.setConfig({ targeting: { interests: "sports" } }); // Setting multiple values for a single targeting key. slot.setConfig({ targeting: { interests: ["sports", "music"] } }); // Setting multiple targeting key-values at once. slot.setConfig({ targeting: { interests: ["sports", "music"], color: "red" } }); // Clearing a single targeting key. slot.setConfig({ targeting: { interests: null } }); // Clear all targeting keys. slot.setConfig({ targeting: null });
- Consulta también
googletag.config.TaxonomyData
Propiedades | |
---|---|
values | Es una lista de valores de Taxonomy. |
Propiedades
values
values: readonly string[]
googletag.config.VideoAdsConfig
Propiedades | |
---|---|
enable | Indica si habrá anuncios de video en la página. |
video | Es el ID de la fuente de contenido de video. |
video | Es el ID de contenido del video. |
- Consulta también
Propiedades
enableVideoAds
enableVideoAds: boolean
Cuando se establece en
true
, se habilitan las restricciones de exclusión de contenido en los anuncios gráficos y de video.Si se conoce el contenido de video, establece videoContentId y videoCmsId en los valores proporcionados al servicio de transferencia de contenido de Google Ad Manager para utilizar la exclusión de contenido en los anuncios gráficos.
Optional
videoCmsId
videoCmsId?: string
Es un valor único que el servicio de transferencia de contenido de Google Ad Manager asigna para identificar la fuente del contenido de video especificado por videoContentId.
- Consulta también
Optional
videoContentId
videoContentId?: string
Es un valor único que identifica un video en particular de la fuente de contenido especificada por videoCmsId. El CMS que aloja tu contenido de video asigna este valor.
- Consulta también
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 la enumeración | |
---|---|
AD_ | Es el formato de intenciones de anuncios. |
BOTTOM_ | Formato de anclaje en el que el espacio se adhiere a la parte inferior del viewport. |
GAME_ | Es el formato de anuncio intersticial manual en juegos. Nota: El anuncio intersticial manual en juegos es un formato de acceso limitado. |
INTERSTITIAL | Es el formato de creatividad de anuncio intersticial para la Web. |
LEFT_ | Es el formato del anuncio lateral izquierdo. |
REWARDED | Es el formato de recompensado. |
RIGHT_ | Es el formato del anuncio fijo lateral derecho. |
TOP_ | Formato de anclaje en el que el espacio publicitario se adhiere 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 seudotipo 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 del manual del juego. |
Game | Este evento se activa cuando un espacio intersticial manual en 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 anuncio recompensado. |
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. |
Rewarded | Este evento se activa cuando finaliza la reproducción de un anuncio de video recompensado. |
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 del anuncio para un espacio en particular. |
Slot | Este evento se activa cada vez que cambia el porcentaje en pantalla del área de un espacio publicitario. |
googletag.events.Event
Propiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. |
slot | Es la ranura 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. |
rewarded | Es un alias de events.RewardedSlotVideoCompletedEvent. |
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
rewardedSlotVideoCompleted
rewardedSlotVideoCompleted: RewardedSlotVideoCompletedEvent
slotOnload
slotOnload: SlotOnloadEvent
slotRenderEnded
slotRenderEnded: SlotRenderEndedEvent
slotRequested
slotRequested: SlotRequestedEvent
slotResponseReceived
slotResponseReceived: SlotResponseReceived
slotVisibilityChanged
slotVisibilityChanged: SlotVisibilityChangedEvent
googletag.events.GameManualInterstitialSlotClosedEvent
ExtiendeNota: El anuncio intersticial manual en juegos es un formato de acceso limitado.
Propiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. Heredado de |
slot | Es la ranura que activó el evento. Heredado 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. Heredado de |
slot | Es la ranura que activó el evento. Heredado 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. Heredado de |
slot | Es la ranura que activó el evento. Heredado 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. Heredado de |
slot | Es la ranura que activó el evento. Heredado 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. Heredado de |
slot | Es la ranura que activó el evento. Heredado 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
payload
payload: RewardedPayload
googletag.events.RewardedSlotReadyEvent
ExtiendePropiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. Heredado de |
slot | Es la ranura que activó el evento. Heredado 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.RewardedSlotVideoCompletedEvent
ExtiendePropiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. Heredado de |
slot | Es la ranura que activó el evento. Heredado 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 video in a rewarded ad slot has // finished playing. googletag.pubads().addEventListener("rewardedSlotVideoCompleted", (event) => { const slot = event.slot; console.log("Video in rewarded ad slot", slot.getSlotElementId(), "has finished playing."); 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 video in a rewarded ad slot has // finished playing. googletag.pubads().addEventListener("rewardedSlotVideoCompleted", function (event) { var slot = event.slot; console.log("Video in rewarded ad slot", slot.getSlotElementId(), "has finished playing."); 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 video in a rewarded ad slot has // finished playing. googletag.pubads().addEventListener("rewardedSlotVideoCompleted", (event) => { const slot = event.slot; console.log("Video in rewarded ad slot", slot.getSlotElementId(), "has finished playing."); if (slot === targetSlot) { // Slot specific logic. } }); }
googletag.events.SlotOnloadEvent
ExtiendeSlotOnloadEvent
.Propiedades | |
---|---|
service | Es el nombre del servicio que activó el evento. Heredado de |
slot | Es la ranura que activó el evento. Heredado 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 | 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 ofertaron por el anuncio de reabastecimiento renderizado. |
creative | ID de la creatividad del anuncio de reserva renderizado. |
creative | ID de la plantilla de creatividad del anuncio de reserva renderizado. |
is | Indica si un anuncio fue de reabastecimiento. |
is | Indica si se devolvió un anuncio para el espacio. |
label | Obsoleto. |
line | Es el ID de la línea de pedido del anuncio de reserva renderizado. |
response | El identificador de respuesta es un identificador único para la respuesta del anuncio. |
service | Es el nombre del servicio que activó el evento. Heredado de |
size | Indica el tamaño en píxeles de la creatividad renderizada. |
slot | Es la ranura que activó el evento. Heredado de |
slot | Indica si el contenido de la ranura se cambió con el anuncio renderizado. |
source | ID de la creatividad del anuncio de reserva o de reabastecimiento renderizado. |
source | Es el ID de la línea de pedido del anuncio de reserva o de reabastecimiento renderizado. |
yield | Son los IDs de los grupos de rendimiento para el anuncio de relleno 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: number
null
para los espacios vacíos, los anuncios de relleno y las creatividades renderizadas por servicios que no sean PubAdsService.campaignId
campaignId: number
null
para los espacios vacíos, los anuncios de relleno y las creatividades renderizadas por servicios que no sean PubAdsService.companyIds
companyIds: number[]
null
para los espacios vacíos, los anuncios de reserva y las creatividades renderizadas por servicios que no sean PubAdsService.creativeId
creativeId: number
null
para los espacios vacíos, los anuncios de relleno y las creatividades renderizadas por servicios que no sean PubAdsService.creativeTemplateId
creativeTemplateId: number
null
para los espacios vacíos, los anuncios de relleno y las creatividades renderizadas por servicios que no sean PubAdsService.isBackfill
isBackfill: boolean
true
si el anuncio fue un anuncio de reabastecimiento y false
en caso contrario.isEmpty
isEmpty: boolean
true
si no se devolvió ningún anuncio y false
en caso contrario.labelIds
labelIds: number[]
lineItemId
lineItemId: number
null
para los espacios vacíos, los anuncios de relleno y las creatividades renderizadas por servicios que no sean PubAdsService.responseIdentifier
responseIdentifier: string
size
size: string | number[]
[728, 90]
. El valor es null
para los espacios publicitarios vacíos.slotContentChanged
slotContentChanged: boolean
true
si se cambió el contenido y false
en caso contrario.sourceAgnosticCreativeId
sourceAgnosticCreativeId: number
null
si el anuncio no es una reserva o un relleno de línea de pedido, o si la creatividad se renderiza a través de servicios distintos de PubAdsService.sourceAgnosticLineItemId
sourceAgnosticLineItemId: number
null
si el anuncio no es una reserva o un relleno de línea de pedido, o si la creatividad se renderiza a través de servicios distintos de PubAdsService.yieldGroupIds
yieldGroupIds: 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. Heredado de |
slot | Es la ranura que activó el evento. Heredado 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. Heredado de |
slot | Es la ranura que activó el evento. Heredado 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. Heredado de |
slot | Es la ranura que activó el evento. Heredado 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 | Devuelve un indicador seguro para un ofertante específico. |
Publisher | Devuelve un indicador seguro para un publicador específico. |
Secure | Es una interfaz para administrar indicadores seguros. |
Alias de tipo | |
---|---|
Secure | Es la interfaz para devolver 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:
- Es una función de recopilación que devuelve un
Promise
que se resuelve en un indicador seguro. - Es un
id
que identifica al ofertante asociado con el indicador.
Propiedades | |
---|---|
collector | Es una función que devuelve un Promise que se resuelve en un indicador seguro. |
id | Es un identificador único del recopilador asociado a este indicador seguro, tal como se registró 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 del publicador consta de 2 partes:
- Es una función de recopilación que devuelve un
Promise
que se resuelve en un indicador seguro. - Es un
networkCode
que identifica al publicador asociado con el indicador.
Propiedades | |
---|---|
collector | Es una función que devuelve un Promise que se resuelve en un indicador seguro. |
network | Es el código de red (como se ve en la ruta de la unidad de anuncios) del publicador asociado a 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
Si se llama a este método, es posible que se reduzca la probabilidad de que se incluyan indicadores en las solicitudes de anuncios para las vistas de página actuales y, posiblemente, posteriores. Por lo tanto, solo se debe llamar cuando se producen cambios de estado significativos, como eventos que indican un usuario nuevo (inicio o cierre de sesión, registro, etcétera).
push
push(provider: SecureSignalProvider): void
Parámetros | |
---|---|
provider: SecureSignalProvider | Es el objeto secureSignals.SecureSignalProvider que se agregará al array. |