В этом справочнике для описания типов используется нотация TypeScript. В следующей таблице приведено краткое объяснение на примере.
| Типовое выражение | |
|---|---|
string | Примитивный строковый тип. |
string[] | Тип массива, значения которого могут быть только строками. |
number | string | Объединенный тип, значение которого может быть либо числом, либо строкой. |
Array<number | string> | Тип массива, значения которого представляют собой комплексные (объединённые) типы. |
[number, string] | Тип кортежа, где значением является массив из двух элементов, который должен содержать число и строку в указанном порядке. |
Slot | Объект типа, значением которого является экземпляр googletag.Slot . |
() => void | Тип функции, не имеющий определённых аргументов и возвращаемого значения. |
Для получения дополнительной информации о поддерживаемых типах и выражениях типов обратитесь к руководству по TypeScript .
Аннотации типов
Двоеточие после имени переменной, параметра, свойства или сигнатуры функции обозначает аннотацию типа. Аннотации типов описывают типы, которые элемент слева от двоеточия может принимать или возвращать. В следующей таблице приведены примеры аннотаций типов, которые вы можете встретить в этом справочнике.
| Аннотация типа | |
|---|---|
param: string | Указывает, что param принимает или возвращает строковое значение. Этот синтаксис используется для переменных, параметров, свойств и типов возвращаемых значений. |
param?: number | string | Указывает, что param является необязательным, но принимает либо число, либо строку при указании. Этот синтаксис используется для параметров и свойств. |
...params: Array<() => void> | Указывает, что params — это параметр REST , принимающий функции. Параметры REST принимают неограниченное количество значений указанного типа. |
Googleтег
| Пространства имен | |
|---|---|
config | Основной интерфейс настройки параметров на уровне страницы. |
enums | Это пространство имен, которое GPT использует для типов перечислений. |
events | Это пространство имен, которое GPT использует для событий. |
secure Signals | Это пространство имен, которое GPT использует для управления защищенными сигналами. |
| Интерфейсы | |
|---|---|
Command Array | Массив команд принимает последовательность функций и вызывает их в указанном порядке. |
Companion Ads Service | Сервис сопутствующей рекламы. |
Privacy Settings Config | Объект конфигурации для настроек конфиденциальности. |
Pub Ads Service | Сервис размещения рекламы для издателей. |
Response Information | Объект, представляющий собой отдельный ответ на рекламное объявление. |
Rewarded Payload | Объект, представляющий собой вознаграждение, связанное с рекламным объявлением, за которое начисляется вознаграждение . |
Service | Базовый класс сервиса, содержащий методы, общие для всех сервисов. |
Size Mapping Builder | Конструктор объектов спецификации сопоставления размеров. |
Slot | Объект Slot представляет собой отдельный рекламный блок на странице. |
| Псевдонимы типов | |
|---|---|
Fluid Size | Строка размера, в которой контейнер рекламы занимает 100% ширины родительского div, а затем изменяет свою высоту в соответствии с размером креативного контента. |
General Size | Допустимая конфигурация размера для слота, которая может включать один или несколько размеров. |
Multi Size | Список допустимых размеров. |
Named Size | Указаны размеры, которые может иметь слот. |
Single Size | Единственный допустимый размер для слота. |
Single Size Array | Массив из двух чисел, представляющих [ширину, высоту]. |
Size Mapping | Сопоставление размера области просмотра с размерами рекламных объявлений. |
Size Mapping Array | Список сопоставлений размеров. |
| Переменные | |
|---|---|
api Ready | Флаг, указывающий на то, что API GPT загружен и готов к вызову. |
cmd | Ссылка на глобальную очередь команд для асинхронного выполнения вызовов, связанных с GPT. |
pubads Ready | Флаг, указывающий на то, что PubAdsService включен, загружен и полностью работоспособен. |
secure Signal Providers | Ссылка на массив поставщиков защищенных сигналов. |
| Функции | |
|---|---|
companion Ads | Возвращает ссылку на CompanionAdsService . |
define Out Of Page Slot | Создает рекламный блок вне страницы, используя указанный путь к рекламному блоку. |
define Slot | Создает рекламный блок с заданным путем и размером и связывает его с идентификатором элемента div на странице, который будет содержать рекламу. |
destroy Slots | Уничтожает указанные слоты, удаляя все связанные с ними объекты и ссылки из GPT. |
disable Publisher Console | Отключает консоль издателя Google. |
display | Дает указание службам слотов отобразить слот. |
enable Services | Включает все сервисы GPT, определенные для рекламных блоков на странице. |
get Config | Получает общие параметры конфигурации страницы, заданные параметром setConfig . |
get Version | Возвращает текущую версию GPT. |
open Console | Открывает консоль издателя Google. |
pubads | Возвращает ссылку на PubAdsService . |
set Ad Iframe Title | Устанавливает заголовок для всех iframe-контейнеров рекламы, создаваемых PubAdsService , начиная с этого момента. |
set Config | Задает общие параметры конфигурации страницы. |
size Mapping | Создает новый объект SizeMappingBuilder . |
Псевдонимы типов
FluidSize
FluidSize : "fluid"GeneralSize
GeneralSize : SingleSize | MultiSizeМногоразмерный
MultiSize : SingleSize []NamedSize
- fluid : рекламный контейнер занимает 100% ширины родительского div, а затем изменяет свою высоту в соответствии с содержимым креатива. Аналогично поведению обычных блочных элементов на странице. Используется для нативной рекламы (см. соответствующую статью ). Обратите внимание, что как
fluid, так и['fluid']являются допустимыми формами для объявления размера рекламного блока как fluid.
Один размер
SingleSize : SingleSizeArray | NamedSizeSingleSizeArray
SingleSizeArray : [ number , number ]SizeMapping
SizeMapping : [ SingleSizeArray , GeneralSize ]SizeMappingArray
SizeMappingArray : SizeMapping []Переменные
Const apiReady
apiReady : boolean | undefinedundefined до тех пор, пока API не будет готов.Обратите внимание, что рекомендуемый способ обработки асинхронных операций — использование googletag.cmd для постановки в очередь обратных вызовов на случай, когда GPT будет готов. Этим обратным вызовам не нужно проверять googletag.apiReady, поскольку их выполнение гарантировано после настройки API.
Const команда
cmd : ( ( this : typeof globalThis ) => void ) [] | CommandArrayПеременная
googletag.cmd инициализируется пустым массивом JavaScript в соответствии с синтаксисом тегов GPT на странице, а cmd.push — это стандартный метод Array.push , который добавляет элемент в конец массива. При загрузке JavaScript-кода GPT он просматривает массив и выполняет все функции по порядку. Затем скрипт заменяет cmd объектом CommandArray , метод push которого определен для выполнения переданного ему аргумента функции. Этот механизм позволяет GPT уменьшить воспринимаемую задержку за счет асинхронной загрузки JavaScript, позволяя браузеру продолжать отрисовку страницы.- Пример
JavaScript
googletag.cmd.push(() => { googletag.defineSlot("/1234567/sports", [160, 600]).addService(googletag.pubads()); });
JavaScript (устаревшая версия)
googletag.cmd.push(function () { googletag.defineSlot("/1234567/sports", [160, 600]).addService(googletag.pubads()); });
Машинопись
googletag.cmd.push(() => { googletag.defineSlot("/1234567/sports", [160, 600])!.addService(googletag.pubads()); });
Const pubadsReady
pubadsReady : boolean | undefinedundefined до тех пор, пока не будет вызван метод enableServices и PubAdsService не будет загружен и инициализирован. secureSignalProviders
secureSignalProviders : SecureSignalProvider [] | SecureSignalProvidersArray | undefinedМассив защищенных поставщиков сигналов принимает последовательность функций генерации сигналов и вызывает их по порядку. Он предназначен для замены стандартного массива, используемого для постановки в очередь функций генерации сигналов, которые будут вызваны после загрузки GPT.
- Пример
JavaScript
window.googletag = window.googletag || { cmd: [] }; googletag.secureSignalProviders = googletag.secureSignalProviders || []; googletag.secureSignalProviders.push({ id: "collector123", collectorFunction: () => { return Promise.resolve("signal"); }, });
JavaScript (устаревшая версия)
window.googletag = window.googletag || { cmd: [] }; googletag.secureSignalProviders = googletag.secureSignalProviders || []; googletag.secureSignalProviders.push({ id: "collector123", collectorFunction: function () { return Promise.resolve("signal"); }, });
Машинопись
window.googletag = window.googletag || { cmd: [] }; googletag.secureSignalProviders = googletag.secureSignalProviders || []; googletag.secureSignalProviders.push({ id: "collector123", collectorFunction: () => { return Promise.resolve("signal"); }, });
Функции
companionAds
companionAds ( ) : CompanionAdsService| Возвраты | |
|---|---|
CompanionAdsService | Сервис сопутствующей рекламы. |
defineOutOfPageSlot
defineOutOfPageSlot ( adUnitPath : string , div ?: string | OutOfPageFormat ) : Slot | nullДля пользовательских рекламных объявлений, размещаемых вне страницы,
div — это идентификатор элемента `div`, который будет содержать объявление. Подробнее см. статью о креативах, размещаемых вне страницы .Для управляемых GPT рекламных объявлений, размещаемых вне страницы,
div является поддерживаемым OutOfPageFormat .- Пример
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 (устаревшая версия)
// 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);
Машинопись
// 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);
- См. также
| Параметры | |
|---|---|
adUnitPath : string | Полный путь к рекламному блоку, включающий сетевой код и код рекламного блока. |
| Идентификатор div, который будет содержать этот рекламный блок, или OutOfPageFormat. |
| Возвраты | |
|---|---|
Slot | null | Вновь созданный слот или null , если слот создать не удаётся. |
defineSlot
defineSlot ( adUnitPath : string , size : GeneralSize , div ?: string ) : Slot | null- Пример
JavaScript
googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
JavaScript (устаревшая версия)
googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
Машинопись
googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
- См. также
| Параметры | |
|---|---|
adUnitPath : string | Полный путь к рекламному блоку, включая сетевой код и код блока. |
size : GeneralSize | Ширина и высота добавляемого слота. Этот размер используется в запросе на показ рекламы, если не указано соответствие размерам для адаптивного отображения или размер области просмотра меньше минимального размера, указанного в соответствии с этим соответствием. |
| Идентификатор div-элемента, который будет содержать этот рекламный блок. |
| Возвраты | |
|---|---|
Slot | null | Вновь созданный слот или null , если слот создать не удаётся. |
destroySlots
destroySlots ( slots ?: Slot [] ) : booleanВызов этого API для слота очищает рекламу и удаляет объект слота из внутреннего состояния, поддерживаемого GPT. Вызов любых других функций для объекта слота приведет к неопределенному поведению. Обратите внимание, что браузер может по-прежнему не освобождать память, связанную с этим слотом, если ссылка на него поддерживается страницей издателя. Вызов этого API делает div, связанный с этим слотом, доступным для повторного использования.
В частности, удаление слота приводит к удалению рекламы из списка долгоживущих просмотров страниц GPT, поэтому будущие запросы не будут зависеть от блокировок или конкурентных исключений, связанных с этой рекламой. Если не вызвать эту функцию перед удалением div слота со страницы, это приведет к неопределенному поведению.
- Пример
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 (устаревшая версия)
// 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();
Машинопись
// 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();
| Параметры | |
|---|---|
| Массив слотов для уничтожения. Массив необязателен; если он не указан, будут уничтожены все слоты. |
| Возвраты | |
|---|---|
boolean | true , если слоты были уничтожены, false в противном случае. |
disablePublisherConsole
disablePublisherConsole ( ) : void- См. также
отображать
display ( divOrSlot : string | Element | Slot ) : voidПри использовании архитектуры с одним запросом (SRA) все невыгруженные на момент вызова этого метода рекламные места будут загружены одновременно. Чтобы принудительно скрыть рекламное место, необходимо удалить весь div-элемент.
- См. также
| Параметры | |
|---|---|
divOrSlot : string | Element | Slot | Либо идентификатор элемента div, содержащего рекламный блок, либо сам элемент div, либо объект рекламного блока. Если указан элемент div, он должен иметь атрибут 'id', соответствующий идентификатору, переданному в функцию defineSlot . |
enableServices
enableServices ( ) : voidgetConfig
getConfig ( keys : string | string [] ) : Pick < PageSettingsConfig , "adsenseAttributes" | "disableInitialLoad" | "targeting" >Этот метод поддерживает не все свойства
setConfig() . Поддерживаются следующие свойства:- Пример
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 (устаревшая версия)
// 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"]);
Машинопись
// 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"]);
| Параметры | |
|---|---|
keys : string | string [] | Ключевые параметры конфигурации, которые необходимо получить. |
| Возвраты | |
|---|---|
Pick < PageSettingsConfig , "adsenseAttributes" | "disableInitialLoad" | "targeting" > | Параметры конфигурации слота. |
получитьВерсию
getVersion ( ) : string- См. также
| Возвраты | |
|---|---|
string | Строка версии GPT, выполняющейся в данный момент. |
openConsole
openConsole ( div ?: string ) : void- Пример
JavaScript
// Calling with div ID. googletag.openConsole("div-1"); // Calling without div ID. googletag.openConsole();
JavaScript (устаревшая версия)
// Calling with div ID. googletag.openConsole("div-1"); // Calling without div ID. googletag.openConsole();
Машинопись
// Calling with div ID. googletag.openConsole("div-1"); // Calling without div ID. googletag.openConsole();
- См. также
| Параметры | |
|---|---|
| Идентификатор div-элемента рекламного блока. Это значение необязательно. Если оно указано, консоль издателя попытается открыться с отображением сведений об указанном рекламном блоке. |
pubads
pubads ( ) : PubAdsService| Возвраты | |
|---|---|
PubAdsService | Сервис Publisher Ads. |
setAdIframeTitle
setAdIframeTitle ( title : string ) : void- Пример
JavaScript
googletag.setAdIframeTitle("title");
JavaScript (устаревшая версия)
googletag.setAdIframeTitle("title");
Машинопись
googletag.setAdIframeTitle("title");
| Параметры | |
|---|---|
title : string | Новое название для всех iframe-контейнеров рекламных объявлений. |
setConfig
setConfig ( config : PageSettingsConfig ) : void| Параметры | |
|---|---|
config : PageSettingsConfig | |
sizeMapping
sizeMapping ( ) : SizeMappingBuilder| Возвраты | |
|---|---|
SizeMappingBuilder | Новый застройщик. |
googletag.CommandArray
| Методы | |
|---|---|
push | Выполняет последовательность функций, указанных в аргументах, в указанном порядке. |
Методы
толкать
push ( ... f : ( ( this : typeof globalThis ) => void ) [] ) : number- Пример
JavaScript
googletag.cmd.push(() => { googletag.defineSlot("/1234567/sports", [160, 600]).addService(googletag.pubads()); });
JavaScript (устаревшая версия)
googletag.cmd.push(function () { googletag.defineSlot("/1234567/sports", [160, 600]).addService(googletag.pubads()); });
Машинопись
googletag.cmd.push(() => { googletag.defineSlot("/1234567/sports", [160, 600])!.addService(googletag.pubads()); });
| Параметры | |
|---|---|
| Функция JavaScript для выполнения. Привязка во время выполнения всегда будет globalThis . Рекомендуется передавать стрелочную функцию для сохранения значения this окружающего лексического контекста. |
| Возвраты | |
|---|---|
number | Количество обработанных команд на данный момент. Это значение совместимо с возвращаемым значением метода Array.push (текущая длина массива). |
googletag.CompanionAdsService
Service| Методы | |
|---|---|
add Event Listener | Регистрирует обработчик событий, позволяющий настроить и вызвать функцию JavaScript при возникновении определенного события GPT на странице. Унаследовано от |
get Slots | Получите список слотов, связанных с этой услугой. Унаследовано от |
remove Event Listener | Удаляет ранее зарегистрированный слушатель. Унаследовано от |
set Refresh Unfilled Slots | Определяет, будут ли незаполненные слоты для компаньонов автоматически заполняться. |
Методы
setRefreshUnfilledSlots
setRefreshUnfilledSlots ( value : boolean ) : voidЭтот метод можно вызывать несколько раз в течение жизненного цикла страницы, чтобы включать и выключать заполнение пустых слотов. Заполняться будут только те слоты, которые также зарегистрированы в PubAdsService . Из-за ограничений политики этот метод не предназначен для заполнения пустых дополнительных слотов при показе видео с Ad Exchange.
- Пример
JavaScript
googletag.companionAds().setRefreshUnfilledSlots(true);
JavaScript (устаревшая версия)
googletag.companionAds().setRefreshUnfilledSlots(true);
Машинопись
googletag.companionAds().setRefreshUnfilledSlots(true);
| Параметры | |
|---|---|
value : boolean | true означает автоматическое заполнение незаполненных слотов, false — оставление их без изменений. |
googletag.PrivacySettingsConfig
| Характеристики | |
|---|---|
child Directed Treatment ? | Указывает, следует ли рассматривать страницу как ориентированную на дочерние элементы . |
limited Ads ? | Позволяет запускать показ рекламы в режиме с ограниченным количеством объявлений , что помогает издателям соблюдать нормативные требования. |
non Personalized Ads ? | Позволяет запускать показ рекламы в режиме без персонализации , что помогает издателям соблюдать нормативные требования. |
restrict Data Processing ? | Позволяет запускать сервис в режиме ограниченной обработки данных для обеспечения соответствия издателя нормативным требованиям. |
traffic Source ? | Указывает, представляют ли запросы купленный или органический трафик. |
under Age Of Consent ? | Указывает, следует ли помечать запросы на рекламу как исходящие от пользователей , не достигших возраста согласия . |
- См. также
Характеристики
Optional лечение, направленное на ребенка
childDirectedTreatment ?: booleannull , чтобы очистить конфигурацию. Optional ограниченное количество объявлений
limitedAds ?: booleanВы можете указать GPT запрашивать показ ограниченного количества рекламы двумя способами:
- Автоматически, с использованием сигнала от платформы управления согласием IAB TCF v2.0 .
- Вручную, установив значение этого поля равным
true.
Обратите внимание, что при использовании CMP нет необходимости вручную включать ограниченное количество рекламы.
- Пример
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 (устаревшая версия)
// Manually enable limited ads serving. // GPT must be loaded from the limited ads URL to configure this setting. googletag.pubads().setPrivacySettings({ limitedAds: true, });
Машинопись
// Manually enable limited ads serving. // GPT must be loaded from the limited ads URL to configure this setting. googletag.pubads().setPrivacySettings({ limitedAds: true, });
- См. также
Optional неперсонализированные объявления
nonPersonalizedAds ?: boolean Optional параметр restrictDataProcessing
restrictDataProcessing ?: boolean Optional источник трафика
trafficSource ?: TrafficSourceundefined .- Пример
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 (устаревшая версия)
// 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, });
Машинопись
// 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 ?: booleannull , чтобы очистить конфигурацию. googletag.PubAdsService
Service| Методы | |
|---|---|
add Event Listener | Регистрирует обработчик событий, позволяющий настроить и вызвать функцию JavaScript при возникновении определенного события GPT на странице. Унаследовано от |
clear | Удаляет рекламу из заданных слотов и заменяет её пустым контентом. |
clear Category Exclusions | Устарело. Удаляет все метки исключения категорий объявлений на уровне страницы. |
clear Targeting | Устарело. Очищает пользовательские параметры таргетинга для конкретного ключа или для всех ключей. |
collapse Empty Divs | Устарело. Позволяет сворачивать блоки div с рекламными объявлениями, чтобы они не занимали место на странице, когда нет рекламного контента для отображения. |
disable Initial Load | Устарело. Отключает запросы на показ рекламы при загрузке страницы, но позволяет запрашивать рекламу с помощью вызова PubAdsService.refresh . |
display | Создает и отображает рекламный блок с заданным путем и размером. |
enable Lazy Load | Устарело. Включает отложенную загрузку в GPT, как определено в объекте конфигурации. |
enable Single Request | Устарело. Включает режим одного запроса для одновременной загрузки нескольких объявлений. |
enable Video Ads | Устарело. Сообщает GPT о том, что на странице будет присутствовать видеореклама. |
get | Устарело. Возвращает значение атрибута AdSense, связанного с заданным ключом. |
get Attribute Keys | Устарело. Возвращает ключи атрибутов, установленные для этой службы. |
get Slots | Получите список слотов, связанных с этой услугой. Унаследовано от |
get Targeting | Устарело. Возвращает заданный пользовательский параметр таргетинга на уровне сервиса. |
get Targeting Keys | Устарело. Возвращает список всех установленных пользовательских ключей таргетинга на уровне сервиса. |
is Initial Load Disabled | Устарело. Возвращает значение, указывающее, был ли успешно отключен первоначальный запрос на показ рекламы предыдущим вызовом PubAdsService.disableInitialLoad . |
refresh | Получает и отображает новые рекламные объявления для определенных или всех рекламных мест на странице. |
remove Event Listener | Удаляет ранее зарегистрированный слушатель. Унаследовано от |
set | Устарело. Устанавливает значения атрибутов AdSense, которые применяются ко всем рекламным местам в рамках сервиса Publisher Ads. |
set Category Exclusion | Устарело. Устанавливает исключение для категории объявлений на уровне страницы для заданного названия метки. |
set Centering | Устарело. Включает и отключает горизонтальное центрирование рекламы. |
set Force Safe Frame | Устарело. Определяет, следует ли принудительно отображать все рекламные объявления на странице с использованием контейнера SafeFrame. |
set Location | Устарело. Передает информацию о местоположении с веб-сайтов, позволяя настраивать географическую привязку позиций заказа к конкретным регионам. |
set Privacy Settings | Позволяет настраивать все параметры конфиденциальности из одного API с помощью объекта конфигурации. |
set Publisher Provided Id | Устанавливает значение для предоставленного издателем идентификатора. |
set Safe Frame Config | Устарело. Задает параметры конфигурации SafeFrame на уровне страницы. |
set Targeting | Устарело. Устанавливает пользовательские параметры таргетинга для заданного ключа, которые применяются ко всем рекламным местам сервиса Publisher Ads. |
set Video Content | Устарело. Задает информацию о видеоконтенте, которая будет отправляться вместе с запросами на показ рекламы для целей таргетинга и исключения контента. |
update Correlator | Изменяет коррелятор, отправляемый вместе с запросами на показ рекламы, фактически запуская новый просмотр страницы. |
Методы
прозрачный
clear ( slots ?: Slot [] ) : booleanВ частности, освобождение места удаляет объявление из списка долгоживущих просмотров страниц GPT, поэтому будущие запросы не будут зависеть от препятствий или конкурентных ограничений, связанных с этим объявлением.
- Пример
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 (устаревшая версия)
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();
Машинопись
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();
| Параметры | |
|---|---|
| Массив слотов для очистки. Массив необязателен; если он не указан, будут очищены все слоты. |
| Возвраты | |
|---|---|
boolean | Возвращает true , если слоты были очищены, false в противном случае. |
clearCategoryExclusions
clearCategoryExclusions ( ) : PubAdsService- Пример
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 (устаревшая версия)
// 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.
Машинопись
// 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.
| Возвраты | |
|---|---|
PubAdsService | Объект сервиса, на котором был вызван метод. |
clearTargeting
clearTargeting ( key ?: string ) : PubAdsService- Пример
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 (устаревшая версия)
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.
Машинопись
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.
- См. также
| Параметры | |
|---|---|
| Ключ параметра таргетинга. Этот ключ необязателен; если он не указан, все параметры таргетинга будут очищены. |
| Возвраты | |
|---|---|
PubAdsService | Объект сервиса, на котором был вызван метод. |
collapseEmptyDivs
collapseEmptyDivs ( collapseBeforeAdFetch ?: boolean ) : boolean| Параметры | |
|---|---|
| Следует ли сворачивать рекламные блоки еще до загрузки объявлений. Этот параметр необязателен; если он не указан, по умолчанию будет использоваться значение false . |
| Возвраты | |
|---|---|
boolean | Возвращает true , если режим сворачивания div был включен, и false если включить режим сворачивания невозможно, поскольку метод был вызван после включения сервиса. |
disableInitialLoad
disableInitialLoad ( ) : voidrefresh будет невозможен.отображать
display ( adUnitPath : string , size : GeneralSize , div ?: string | Element , clickUrl ?: string ) : voidЭтот метод является сокращенным эквивалентом вызова googletag.defineSlot с последующим немедленным вызовом googletag.display .
Поведение этого метода зависит от того, включена ли архитектура единого запроса (SRA) :
- SRA включено: Все рекламные места, определенные к моменту этого вызова, будут объединены в пакет и запрошены одновременно.
- SRA отключено (по умолчанию): запрос на размещение рекламы будет отправлен индивидуально.
display() или refresh() .- Пример
JavaScript
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
JavaScript (устаревшая версия)
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
Машинопись
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
| Параметры | |
|---|---|
adUnitPath : string | Путь к рекламному блоку в слоте, который необходимо отобразить. |
size : GeneralSize | Ширина и высота паза. |
| Либо идентификатор div, содержащего слот, либо сам элемент div. |
| URL-адрес клика, который следует использовать для этого слота. |
enableLazyLoad
enableLazyLoad ( config ?: {
fetchMarginPercent ?: number ;
mobileScaling ?: number ;
renderMarginPercent ?: number ;
} ) : voidПримечание: Ленивая выборка в SRA работает только в том случае, если все слоты находятся за пределами области выборки.
- Пример
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 (устаревшая версия)
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, });
Машинопись
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, });
- См. также
| Параметры | |
|---|---|
| Объект конфигурации позволяет настраивать поведение отложенной загрузки. Любые пропущенные параметры конфигурации будут использовать значение по умолчанию, установленное Google, которое будет корректироваться со временем. Чтобы отключить определенный параметр, например, отступ при получении данных, установите значение -1 .
|
enableSingleRequest
enableSingleRequest ( ) : boolean- См. также
| Возвраты | |
|---|---|
boolean | Возвращает true , если режим одного запроса был включен, и false если включить режим одного запроса невозможно, поскольку метод был вызван после включения службы. |
включитьВидеорекламу
enableVideoAds ( ) : voidполучать
get ( key : string ) : string- Пример
JavaScript
googletag.pubads().set("adsense_background_color", "#FFFFFF"); googletag.pubads().get("adsense_background_color"); // Returns '#FFFFFF'.
JavaScript (устаревшая версия)
googletag.pubads().set("adsense_background_color", "#FFFFFF"); googletag.pubads().get("adsense_background_color"); // Returns '#FFFFFF'.
Машинопись
googletag.pubads().set("adsense_background_color", "#FFFFFF"); googletag.pubads().get("adsense_background_color"); // Returns '#FFFFFF'.
- См. также
| Параметры | |
|---|---|
key : string | Название атрибута, который необходимо проверить. |
| Возвраты | |
|---|---|
string | Текущее значение для ключа атрибута или null , если ключ отсутствует. |
getAttributeKeys
getAttributeKeys ( ) : string []- Пример
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 (устаревшая версия)
googletag.pubads().set("adsense_background_color", "#FFFFFF"); googletag.pubads().set("adsense_border_color", "#AABBCC"); googletag.pubads().getAttributeKeys(); // Returns ['adsense_background_color', 'adsense_border_color'].
Машинопись
googletag.pubads().set("adsense_background_color", "#FFFFFF"); googletag.pubads().set("adsense_border_color", "#AABBCC"); googletag.pubads().getAttributeKeys(); // Returns ['adsense_background_color', 'adsense_border_color'].
| Возвраты | |
|---|---|
string [] | Массив ключей атрибутов, заданных для этой службы. Порядок не определен. |
getTargeting
getTargeting ( key : string ) : string []- Пример
JavaScript
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().getTargeting("interests"); // Returns ['sports']. googletag.pubads().getTargeting("age"); // Returns [] (empty array).
JavaScript (устаревшая версия)
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().getTargeting("interests"); // Returns ['sports']. googletag.pubads().getTargeting("age"); // Returns [] (empty array).
Машинопись
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().getTargeting("interests"); // Returns ['sports']. googletag.pubads().getTargeting("age"); // Returns [] (empty array).
| Параметры | |
|---|---|
key : string | Ключ к нацеливанию, на который следует обратить внимание. |
| Возвраты | |
|---|---|
string [] | Значения, связанные с этим ключом, или пустой массив, если такого ключа нет. |
getTargetingKeys
getTargetingKeys ( ) : string []- Пример
JavaScript
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().setTargeting("colors", "blue"); googletag.pubads().getTargetingKeys(); // Returns ['interests', 'colors'].
JavaScript (устаревшая версия)
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().setTargeting("colors", "blue"); googletag.pubads().getTargetingKeys(); // Returns ['interests', 'colors'].
Машинопись
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().setTargeting("colors", "blue"); googletag.pubads().getTargetingKeys(); // Returns ['interests', 'colors'].
| Возвраты | |
|---|---|
string [] | Массив целевых ключей. Порядок не определен. |
isInitialLoadDisabled
isInitialLoadDisabled ( ) : boolean| Возвраты | |
|---|---|
boolean | Возвращает true если предыдущий вызов PubAdsService.disableInitialLoad был успешным, в противном случае false . |
обновить
refresh ( slots ?: Slot [] , options ?: {
changeCorrelator : boolean ;
} ) : voidДля корректной работы во всех браузерах вызов функции
refresh должен предшествовать вызову функции display для display рекламного блока. Если вызов display опущен, функция refresh может работать некорректно. При желании можно использовать метод PubAdsService.disableInitialLoad , чтобы предотвратить загрузку рекламы функцией display .Обновление рекламного блока удаляет старую рекламу из списка долгоживущих просмотров страниц GPT, поэтому будущие запросы не будут зависеть от препятствий или конкурентных ограничений, связанных с этой рекламой.
- Пример
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 (устаревшая версия)
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 });
Машинопись
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 });
| Параметры | |
|---|---|
| Слоты для обновления. Массив является необязательным; если он не указан, будут обновлены все слоты. |
| Параметры конфигурации, связанные с этим вызовом обновления.
|
набор
set ( key : string , value : string ) : PubAdsServiceПовторный вызов этой функции для одного и того же ключа приведет к переопределению ранее установленных значений для этого ключа. Все значения должны быть установлены до вызова
display или refresh .- Пример
JavaScript
googletag.pubads().set("adsense_background_color", "#FFFFFF");
JavaScript (устаревшая версия)
googletag.pubads().set("adsense_background_color", "#FFFFFF");
Машинопись
googletag.pubads().set("adsense_background_color", "#FFFFFF");
- См. также
| Параметры | |
|---|---|
key : string | Название атрибута. |
value : string | Значение атрибута. |
| Возвраты | |
|---|---|
PubAdsService | Объект сервиса, на котором был вызван метод. |
setCategoryExclusion
setCategoryExclusion ( categoryExclusion : string ) : PubAdsService- Пример
JavaScript
// Label = AirlineAd. googletag.pubads().setCategoryExclusion("AirlineAd");
JavaScript (устаревшая версия)
// Label = AirlineAd. googletag.pubads().setCategoryExclusion("AirlineAd");
Машинопись
// Label = AirlineAd. googletag.pubads().setCategoryExclusion("AirlineAd");
| Параметры | |
|---|---|
categoryExclusion : string | Добавить метку исключения категории объявления. |
| Возвраты | |
|---|---|
PubAdsService | Объект сервиса, на котором был вызван метод. |
setCentering
setCentering ( centerAds : boolean ) : voidЭтот метод следует вызывать перед вызовом
display или refresh поскольку центрированию подлежат только объявления, запрошенные после вызова этого метода.- Пример
JavaScript
// Make ads centered. googletag.pubads().setCentering(true);
JavaScript (устаревшая версия)
// Make ads centered. googletag.pubads().setCentering(true);
Машинопись
// Make ads centered. googletag.pubads().setCentering(true);
| Параметры | |
|---|---|
centerAds : boolean | true — выравнивание рекламы по центру, false — выравнивание по левому краю. |
setForceSafeFrame
setForceSafeFrame ( forceSafeFrame : boolean ) : PubAdsServiceПри использовании этого API, пожалуйста, учитывайте следующие моменты:
- Эта настройка будет действовать только при последующих запросах рекламы, сделанных для соответствующих рекламных мест.
- Если указан параметр уровня слота, он всегда будет иметь приоритет над параметром уровня страницы.
- Если установлено значение
true(на уровне слота или страницы), объявление всегда будет отображаться с использованием контейнера SafeFrame независимо от выбора, сделанного в пользовательском интерфейсе Google Ad Manager. - Однако, если установить значение
falseили оставить параметр неуказанным, объявление будет отображаться с использованием контейнера SafeFrame в зависимости от типа креатива и выбора, сделанного в пользовательском интерфейсе Google Ad Manager. - Этот API следует использовать с осторожностью, поскольку он может повлиять на поведение рекламных материалов, которые пытаются выйти за пределы своих iFrames или полагаются на их прямую отрисовку на странице издателя.
- Пример
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 (устаревшая версия)
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");
Машинопись
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");
| Параметры | |
|---|---|
forceSafeFrame : boolean | true принудительно устанавливает отображение всей рекламы на странице в SafeFrames, а false отменяет предыдущую настройку. Установка значения false , если оно ранее не было указано, ничего не изменит. |
| Возвраты | |
|---|---|
PubAdsService | Объект сервиса, на котором был вызван метод. |
setLocation
setLocation ( address : string ) : PubAdsService- Пример
JavaScript
// Postal code: googletag.pubads().setLocation("10001,US");
JavaScript (устаревшая версия)
// Postal code: googletag.pubads().setLocation("10001,US");
Машинопись
// Postal code: googletag.pubads().setLocation("10001,US");
| Параметры | |
|---|---|
address : string | Адрес в свободной форме. |
| Возвраты | |
|---|---|
PubAdsService | Объект сервиса, на котором был вызван метод. |
setPrivacySettings
setPrivacySettings ( privacySettings : PrivacySettingsConfig ) : PubAdsService- Пример
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 (устаревшая версия)
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, });
Машинопись
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, });
| Параметры | |
|---|---|
privacySettings : PrivacySettingsConfig | Объект, содержащий конфигурацию настроек конфиденциальности. |
| Возвраты | |
|---|---|
PubAdsService | Объект сервиса, на котором была вызвана функция. |
setPublisherProvidedId
setPublisherProvidedId ( ppid : string ) : PubAdsService- Пример
JavaScript
googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
JavaScript (устаревшая версия)
googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
Машинопись
googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
| Параметры | |
|---|---|
ppid : string | Буквенно-цифровой идентификатор, предоставленный издателем. Должен содержать от 32 до 150 символов. |
| Возвраты | |
|---|---|
PubAdsService | Объект сервиса, на котором был вызван метод. |
setSafeFrameConfig
setSafeFrameConfig ( config : SafeFrameConfig ) : PubAdsServiceЭти настройки на уровне страницы будут переопределены настройками на уровне слота, если таковые указаны.
- Пример
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 (устаревшая версия)
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");
Машинопись
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");
| Параметры | |
|---|---|
config : SafeFrameConfig | Объект конфигурации. |
| Возвраты | |
|---|---|
PubAdsService | Объект сервиса, на котором был вызван метод. |
setTargeting
setTargeting ( key : string , value : string | string [] ) : PubAdsService- Пример
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 (устаревшая версия)
// 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"]);
Машинопись
// 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"]);
- См. также
| Параметры | |
|---|---|
key : string | Ключ параметра таргетинга. |
value : string | string [] | Укажите значение параметра или массив значений, на которые будет направлено действие. |
| Возвраты | |
|---|---|
PubAdsService | Объект сервиса, на котором был вызван метод. |
setVideoContent
setVideoContent ( videoContentId : string , videoCmsId : string ) : voidvideoContentId и videoCmsId используйте значения, предоставленные службе загрузки контента Google Ad Manager.| Параметры | |
|---|---|
videoContentId : string | Идентификатор видеоконтента. |
videoCmsId : string | Идентификатор видео CMS. |
updateCorrelator
updateCorrelator ( ) : PubAdsServiceПримечание: это никак не влияет на функцию «Длительный просмотр страницы» в GPT, которая автоматически отображает фактически размещенные на странице объявления и не имеет срока действия.
- Пример
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 (устаревшая версия)
// 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.
Машинопись
// 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.
| Возвраты | |
|---|---|
PubAdsService | Объект сервиса, на котором была вызвана функция. |
googletag.ResponseInformation
| Характеристики | |
|---|---|
advertiser Id | Идентификатор рекламодателя. |
campaign Id | Идентификатор кампании. |
creative Id | Идентификатор креатива. |
creative Template Id | Идентификатор шаблона объявления. |
line Item Id | Идентификатор позиции заказа. |
- См. также
Характеристики
advertiserId
advertiserId : numbercampaignId
campaignId : numberкреативный ID
creativeId : numbercreativeTemplateId
creativeTemplateId : numberlineItemId
lineItemId : numbergoogletag.RewardedPayload
| Характеристики | |
|---|---|
amount | Количество предметов, входящих в состав награды. |
type | Тип предмета, входящего в состав награды (например, «монета»). |
- См. также
Характеристики
количество
amount : numberтип
type : stringgoogletag.Service
| Методы | |
|---|---|
add Event Listener | Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page. |
get Slots | Get the list of slots associated with this service. |
remove Event Listener | Removes a previously registered listener. |
Методы
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
- Пример
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 (legacy)
// 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. } });
Машинопись
// 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. } });
- См. также
| Параметры | |
|---|---|
eventType : K | A string representing the type of event generated by GPT. Event types are case sensitive. |
listener : ( ( arg : EventTypeMap [ K ] ) => void ) | Function that takes a single event object argument. |
| Возвраты | |
|---|---|
Service | The service object on which the method was called. |
getSlots
removeEventListener
removeEventListener < K extends keyof EventTypeMap > ( eventType : K , listener : ( ( event : EventTypeMap [ K ] ) => void ) ) : void- Пример
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 (legacy)
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(); });
Машинопись
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(); });
| Параметры | |
|---|---|
eventType : K | A string representing the type of event generated by GPT. Event types are case sensitive. |
listener : ( ( event : EventTypeMap [ K ] ) => void ) | Function that takes a single event object argument. |
googletag.SizeMappingBuilder
| Методы | |
|---|---|
add Size | Adds a mapping from a single-size array (representing the viewport) to a single- or multi-size array representing the slot. |
build | Builds a size map specification from the mappings added to this builder. |
- См. также
Методы
addSize
addSize ( viewportSize : SingleSizeArray , slotSize : GeneralSize ) : SizeMappingBuilder- Пример
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 (legacy)
// 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]
Машинопись
// 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]
| Параметры | |
|---|---|
viewportSize : SingleSizeArray | The size of the viewport for this mapping entry. |
slotSize : GeneralSize | The sizes of the slot for this mapping entry. |
| Возвраты | |
|---|---|
SizeMappingBuilder | A reference to this builder. |
строить
build ( ) : SizeMappingArrayIf any invalid mappings have been supplied, this method will return
null . Otherwise it returns a specification in the correct format to pass to Slot.defineSizeMapping .Note: the behavior of the builder after calling this method is undefined.
| Возвраты | |
|---|---|
SizeMappingArray | The result built by this builder. Can be null if invalid size mappings were supplied. |
googletag.Slot
| Методы | |
|---|---|
add Service | Adds a Service to this slot. |
clear Category Exclusions | Deprecated. Clears all slot-level ad category exclusion labels for this slot. |
clear Targeting | Deprecated. Clears specific or all custom slot-level targeting parameters for this slot. |
define Size Mapping | Sets an array of mappings from a minimum viewport size to slot size for this slot. |
get | Deprecated. Returns the value for the AdSense attribute associated with the given key for this slot. |
get Ad Unit Path | Returns the full path of the ad unit, with the network code and ad unit path. |
get Attribute Keys | Deprecated. Returns the list of attribute keys set on this slot. |
get Category Exclusions | Deprecated. Returns the ad category exclusion labels for this slot. |
get Config | Gets general configuration options for the slot set by setConfig . |
get Response Information | Returns the ad response information. |
get Slot Element Id | Returns the ID of the slot div provided when the slot was defined. |
get Targeting | Deprecated. Returns a specific custom targeting parameter set on this slot. |
get Targeting Keys | Deprecated. Returns the list of all custom targeting keys set on this slot. |
set | Deprecated. Sets a value for an AdSense attribute on this ad slot. |
set Category Exclusion | Deprecated. Sets a slot-level ad category exclusion label on this slot. |
set Click Url | Deprecated. Sets the click URL to which users will be redirected after clicking on the ad. |
set Collapse Empty Div | Deprecated. Sets whether the slot div should be hidden when there is no ad in the slot. |
set Config | Sets general configuration options for this slot. |
set Force Safe Frame | Deprecated. Configures whether ads in this slot should be forced to be rendered using a SafeFrame container. |
set Safe Frame Config | Deprecated. Sets the slot-level preferences for SafeFrame configuration. |
set Targeting | Deprecated. Sets a custom targeting parameter for this slot. |
update Targeting From Map | Deprecated. Sets custom targeting parameters for this slot, from a key:value map in a JSON object. |
Методы
addService
addService ( service : Service ) : Slot- Пример
JavaScript
googletag.defineSlot("/1234567/sports", [160, 600], "div").addService(googletag.pubads());
JavaScript (legacy)
googletag.defineSlot("/1234567/sports", [160, 600], "div").addService(googletag.pubads());
Машинопись
googletag.defineSlot("/1234567/sports", [160, 600], "div")!.addService(googletag.pubads());
| Параметры | |
|---|---|
service : Service | The service to be added. |
| Возвраты | |
|---|---|
Slot | The slot object on which the method was called. |
clearCategoryExclusions
clearCategoryExclusions ( ) : Slot- Пример
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 (legacy)
// 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.
Машинопись
// 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.
| Возвраты | |
|---|---|
Slot | The slot object on which the method was called. |
clearTargeting
clearTargeting ( key ?: string ) : Slot- Пример
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 (legacy)
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.
Машинопись
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.
- См. также
| Параметры | |
|---|---|
| Targeting parameter key. The key is optional; all targeting parameters will be cleared if it is unspecified. |
| Возвраты | |
|---|---|
Slot | The slot object on which the method was called. |
defineSizeMapping
defineSizeMapping ( sizeMapping : SizeMappingArray ) : Slot- Пример
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 (legacy)
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);
Машинопись
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!);
- См. также
| Параметры | |
|---|---|
sizeMapping : SizeMappingArray | Array of size mappings. You can use SizeMappingBuilder to create it. Each size mapping is an array of two elements: SingleSizeArray and GeneralSize . |
| Возвраты | |
|---|---|
Slot | The slot object on which the method was called. |
получать
get ( key : string ) : string- Пример
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 (legacy)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .set("adsense_background_color", "#FFFFFF") .addService(googletag.pubads()); slot.get("adsense_background_color"); // Returns '#FFFFFF'.
Машинопись
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .set("adsense_background_color", "#FFFFFF") .addService(googletag.pubads()); slot.get("adsense_background_color"); // Returns '#FFFFFF'.
- См. также
| Параметры | |
|---|---|
key : string | Name of the attribute to look for. |
| Возвраты | |
|---|---|
string | Current value for the attribute key, or null if the key is not present. |
getAdUnitPath
getAdUnitPath ( ) : string- Пример
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); slot.getAdUnitPath(); // Returns '/1234567/sports'.
JavaScript (legacy)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); slot.getAdUnitPath(); // Returns '/1234567/sports'.
Машинопись
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); slot.getAdUnitPath(); // Returns '/1234567/sports'.
| Возвраты | |
|---|---|
string | Ad unit path. |
getAttributeKeys
getAttributeKeys ( ) : string []- Пример
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 (legacy)
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'].
Машинопись
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'].
| Возвраты | |
|---|---|
string [] | Array of attribute keys. Ordering is undefined. |
getCategoryExclusions
getCategoryExclusions ( ) : string []- Пример
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setCategoryExclusion("AirlineAd") .setCategoryExclusion("TrainAd") .addService(googletag.pubads()); slot.getCategoryExclusions(); // Returns ['AirlineAd', 'TrainAd'].
JavaScript (legacy)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setCategoryExclusion("AirlineAd") .setCategoryExclusion("TrainAd") .addService(googletag.pubads()); slot.getCategoryExclusions(); // Returns ['AirlineAd', 'TrainAd'].
Машинопись
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .setCategoryExclusion("AirlineAd") .setCategoryExclusion("TrainAd") .addService(googletag.pubads()); slot.getCategoryExclusions(); // Returns ['AirlineAd', 'TrainAd'].
| Возвраты | |
|---|---|
string [] | The ad category exclusion labels for this slot, or an empty array if none have been set. |
getConfig
getConfig ( keys : string | string [] ) : Pick < SlotSettingsConfig , "adsenseAttributes" | "targeting" | "categoryExclusion" >Not all
setConfig() properties are supported by this method. Supported properties are:- Пример
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 (legacy)
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"]);
Машинопись
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"]);
| Параметры | |
|---|---|
keys : string | string [] | The keys of the configuration options to get. |
| Возвраты | |
|---|---|
Pick < SlotSettingsConfig , "adsenseAttributes" | "targeting" | "categoryExclusion" > | The configuration options for the slot. |
getResponseInformation
getResponseInformation ( ) : ResponseInformationnull will be returned. | Возвраты | |
|---|---|
ResponseInformation | The latest ad response information, or null if the slot has no ad. |
getSlotElementId
getSlotElementId ( ) : stringdiv provided when the slot was defined.- Пример
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); slot.getSlotElementId(); // Returns 'div'.
JavaScript (legacy)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); slot.getSlotElementId(); // Returns 'div'.
Машинопись
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); slot.getSlotElementId(); // Returns 'div'.
| Возвраты | |
|---|---|
string | Slot div ID. |
getTargeting
getTargeting ( key : string ) : string []- Пример
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 (legacy)
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).
Машинопись
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).
| Параметры | |
|---|---|
key : string | The targeting key to look for. |
| Возвраты | |
|---|---|
string [] | The values associated with this key, or an empty array if there is no such key. |
getTargetingKeys
getTargetingKeys ( ) : string []- Пример
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 (legacy)
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'].
Машинопись
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'].
| Возвраты | |
|---|---|
string [] | Array of targeting keys. Ordering is undefined. |
набор
set ( key : string , value : string ) : SlotCalling this method more than once for the same key will override previously set values for that key. All values must be set before calling
display or refresh .- Пример
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 (legacy)
// Setting an attribute on a single ad slot. googletag .defineSlot("/1234567/sports", [160, 600], "div") .set("adsense_background_color", "#FFFFFF") .addService(googletag.pubads());
Машинопись
// Setting an attribute on a single ad slot. googletag .defineSlot("/1234567/sports", [160, 600], "div")! .set("adsense_background_color", "#FFFFFF") .addService(googletag.pubads());
- См. также
| Параметры | |
|---|---|
key : string | The name of the attribute. |
value : string | Attribute value. |
| Возвраты | |
|---|---|
Slot | The slot object on which the method was called. |
setCategoryExclusion
setCategoryExclusion ( categoryExclusion : string ) : Slot- Пример
JavaScript
// Label = AirlineAd googletag .defineSlot("/1234567/sports", [160, 600], "div") .setCategoryExclusion("AirlineAd") .addService(googletag.pubads());
JavaScript (legacy)
// Label = AirlineAd googletag .defineSlot("/1234567/sports", [160, 600], "div") .setCategoryExclusion("AirlineAd") .addService(googletag.pubads());
Машинопись
// Label = AirlineAd googletag .defineSlot("/1234567/sports", [160, 600], "div")! .setCategoryExclusion("AirlineAd") .addService(googletag.pubads());
- См. также
| Параметры | |
|---|---|
categoryExclusion : string | The ad category exclusion label to add. |
| Возвраты | |
|---|---|
Slot | The slot object on which the method was called. |
setClickUrl
setClickUrl ( value : string ) : SlotThe Google Ad Manager servers still record a click even if the click URL is replaced. Any landing page URL associated with the creative that is served is appended to the provided value. Subsequent calls overwrite the value. This works only for non-SRA requests.
- Пример
JavaScript
googletag .defineSlot("/1234567/sports", [160, 600], "div") .setClickUrl("http://www.example.com?original_click_url=") .addService(googletag.pubads());
JavaScript (legacy)
googletag .defineSlot("/1234567/sports", [160, 600], "div") .setClickUrl("http://www.example.com?original_click_url=") .addService(googletag.pubads());
Машинопись
googletag .defineSlot("/1234567/sports", [160, 600], "div")! .setClickUrl("http://www.example.com?original_click_url=") .addService(googletag.pubads());
| Параметры | |
|---|---|
value : string | The click URL to set. |
| Возвраты | |
|---|---|
Slot | The slot object on which the method was called. |
setCollapseEmptyDiv
setCollapseEmptyDiv ( collapse : boolean , collapseBeforeAdFetch ?: boolean ) : Slotdiv should be hidden when there is no ad in the slot. This overrides the service-level settings.- Пример
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 (legacy)
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.
Машинопись
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.
- См. также
| Параметры | |
|---|---|
collapse : boolean | Whether to collapse the slot if no ad is returned. |
| Whether to collapse the slot even before an ad is fetched. Ignored if collapse is not true . |
| Возвраты | |
|---|---|
Slot | The slot object on which the method was called. |
setConfig
setConfig ( slotConfig : SlotSettingsConfig ) : void| Параметры | |
|---|---|
slotConfig : SlotSettingsConfig | The configuration object. |
setForceSafeFrame
setForceSafeFrame ( forceSafeFrame : boolean ) : SlotPlease keep the following things in mind while using this API:
- This setting will only take effect for subsequent ad requests made for the respective slots.
- The slot level setting, if specified, will always override the page level setting.
- If set to
true(at slot-level or page level), the ad will always be rendered using a SafeFrame container independent of the choice made in the Google Ad Manager UI. - However, if set to
falseor left unspecified, the ad will be rendered using a SafeFrame container depending on the type of creative and the selection made in the Google Ad Manager UI. - This API should be used with caution as it could impact the behaviour of creatives that attempt to break out of their iFrames or rely on them being rendered directly in a publishers page.
- Пример
JavaScript
googletag .defineSlot("/1234567/sports", [160, 600], "div") .setForceSafeFrame(true) .addService(googletag.pubads());
JavaScript (legacy)
googletag .defineSlot("/1234567/sports", [160, 600], "div") .setForceSafeFrame(true) .addService(googletag.pubads());
Машинопись
googletag .defineSlot("/1234567/sports", [160, 600], "div")! .setForceSafeFrame(true) .addService(googletag.pubads());
- См. также
| Параметры | |
|---|---|
forceSafeFrame : boolean | true to force all ads in this slot to be rendered in SafeFrames and false to opt-out of a page-level setting (if present). Setting this to false when not specified at the page-level won't change anything. |
| Возвраты | |
|---|---|
Slot | The slot object on which the method was called. |
setSafeFrameConfig
setSafeFrameConfig ( config : SafeFrameConfig ) : SlotThese slot-level preferences, if specified, will override any page-level preferences.
- Пример
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 (legacy)
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");
Машинопись
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");
- См. также
| Параметры | |
|---|---|
config : SafeFrameConfig | The configuration object. |
| Возвраты | |
|---|---|
Slot | The slot object on which the method was called. |
setTargeting
setTargeting ( key : string , value : string | string [] ) : Slot- Пример
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 (legacy)
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"]);
Машинопись
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"]);
- См. также
| Параметры | |
|---|---|
key : string | Targeting parameter key. |
value : string | string [] | Targeting parameter value or array of values. |
| Возвраты | |
|---|---|
Slot | The slot object on which the method was called. |
updateTargetingFromMap
updateTargetingFromMap ( map : {
[ adUnitPath : string ] : string | string [] ;
} ) : SlotПримечания:
- In case of overwriting, only the last value will be kept.
- If the value is an array, any previous value will be overwritten, not merged.
- Values set here will overwrite targeting parameters set at the service-level.
- Пример
JavaScript
const slot = googletag.defineSlot("/1234567/sports", [160, 600], "div"); slot.updateTargetingFromMap({ color: "red", interests: ["sports", "music", "movies"], });
JavaScript (legacy)
var slot = googletag.defineSlot("/1234567/sports", [160, 600], "div"); slot.updateTargetingFromMap({ color: "red", interests: ["sports", "music", "movies"], });
Машинопись
const slot = googletag.defineSlot("/1234567/sports", [160, 600], "div")!; slot.updateTargetingFromMap({ color: "red", interests: ["sports", "music", "movies"], });
| Параметры | |
|---|---|
map : { | Targeting parameter key:value map. |
| Возвраты | |
|---|---|
Slot | The slot object on which the method was called. |
googletag.config
| Интерфейсы | |
|---|---|
Ad Expansion Config | Settings to control ad expansion. |
Ad Sense Attributes Config | Settings to control the behavior of AdSense ads. |
Component Auction Config | An object representing a single component auction in a on-device ad auction. |
Interstitial Config | An object which defines the behavior of a single interstitial ad slot. |
Lazy Load Config | Settings to control the use of lazy loading in GPT. |
Page Settings Config | Main configuration interface for page-level settings. |
Privacy Treatments Config | Settings to control publisher privacy treatments. |
Publisher Provided Signals Config | Publisher provided signals (PPS) configuration object. |
Safe Frame Config | Settings to control SafeFrame in GPT. |
Slot Settings Config | Main configuration interface for slot-level settings. |
Taxonomy Data | An object containing the values for a single Taxonomy . |
Video Ads Config | Settings to configure video ad related settings. |
| Псевдонимы типов | |
|---|---|
Collapse Div Behavior | Supported values for controlling the collapsing behavior of ad slots. |
Interstitial Trigger | Supported interstitial ad triggers. |
Privacy Treatment | Supported publisher privacy treatments. |
Taxonomy | Supported taxonomies for publisher provided signals (PPS) . |
Псевдонимы типов
CollapseDivBehavior
CollapseDivBehavior : "DISABLED" | "BEFORE_FETCH" | "ON_NO_FILL"InterstitialTrigger
InterstitialTrigger : "unhideWindow" | "navBar"PrivacyTreatment
PrivacyTreatment : "disablePersonalization"Таксономия
Taxonomy : "IAB_AUDIENCE_1_1" | "IAB_CONTENT_2_2"googletag.config.AdExpansionConfig
| Характеристики | |
|---|---|
enabled ? | Whether ad expansion is enabled or disabled. |
- Пример
JavaScript
// Enable ad slot expansion across the entire page. googletag.setConfig({ adExpansion: { enabled: true }, });
JavaScript (legacy)
// Enable ad slot expansion across the entire page. googletag.setConfig({ adExpansion: { enabled: true }, });
Машинопись
// Enable ad slot expansion across the entire page. googletag.setConfig({ adExpansion: { enabled: true }, });
Характеристики
Optional enabled
enabled ?: booleanSetting this value overrides the default configured in Google Ad Manager.
googletag.config.AdSenseAttributesConfig
These attributes can be used to override server-side settings on a per-request basis.
| Характеристики | |
|---|---|
adsense _ad _format ? | AdSense ad format. |
adsense _channel _ids ? | AdSense channel IDs. |
adsense _test _mode ? | Whether or not test mode is enabled. |
document _language ? | Language of the page on which ads are displayed. |
page _url ? | URL of the page on which ads are displayed. |
Характеристики
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 ?: stringAllowed values are channel IDs separated by '+'.
Example:
271828183+314159265 Optional adsense_test_mode
adsense_test_mode ?: "on"When set to
on , ads are marked as test-only, and won't be included in counting or billing. This setting must be unset for production, non-test traffic. Optional document_language
document_language ?: stringAllowed values are valid ISO 639-1 language codes.
Example:
en- См. также
Optional page_url
page_url ?: stringAllowed values are valid URLs.
Example:
http://www.example.com googletag.config.ComponentAuctionConfig
| Характеристики | |
|---|---|
auction Config | An auction configuration object for this component auction. |
config Key | The configuration key associated with this component auction. |
Характеристики
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 ;
}If this value is set to
null , any existing configuration for the specified configKey will be deleted.- Пример
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 (legacy)
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, }, ], });
Машинопись
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 : stringThis value must be non-empty and should be unique. If two
ComponentAuctionConfig objects share the same configKey value, the last to be set will overwrite prior configurations. googletag.config.InterstitialConfig
| Характеристики | |
|---|---|
require Storage Access ? | Whether local storage consent is required to display this interstitial ad. |
triggers ? | The interstitial trigger configuration for this interstitial ad. |
Характеристики
Optional requireStorageAccess
requireStorageAccess ?: booleanGPT uses local storage to enforce a frequency cap for interstitial ads. However, users who have not provided local storage consent are still eligible to be served interstitial ads. Setting this property to
true opts out of the default behavior, and ensures interstial ads are only shown to users who have provided local storage consent.- Пример
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 (legacy)
// 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 }, });
Машинопись
// 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 }, });
- См. также
Optional triggers
triggers ?: Partial < Record < InterstitialTrigger , boolean > >Setting the value of an interstitial trigger to
true will enable it and false will disable it. This will override the default values configured in Google Ad Manager .- Пример
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 (legacy)
// 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, }, }, });
Машинопись
// 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, }, }, });
- См. также
googletag.config.LazyLoadConfig
| Характеристики | |
|---|---|
fetch Margin Percent ? | The minimum distance from the current viewport a slot must be before we request an ad, expressed as a percentage of viewport size. |
mobile Scaling ? | A multiplier applied to margins on mobile devices. |
render Margin Percent ? | The minimum distance from the current viewport a slot must be before we render an ad, expressed as a percentage of viewport size. |
- См. также
Характеристики
Optional fetchMarginPercent
fetchMarginPercent ?: numberUsed in conjunction with renderMarginPercent , this setting allows for prefetching an ad, but waiting to render and download other subresources. As such, this value should always be greater than or equal to renderMarginPercent .
A value of
0 means "when the slot enters the viewport", 100 means "when the ad is 1 viewport away", and so on. Optional mobileScaling
mobileScaling ?: numberThis allows for different margins on mobile vs. desktop, where viewport sizes and scroll speeds may be different. For example, a value of 2.0 will multiply all margins by 2 on mobile devices, increasing the minimum distance a slot can be from the viewport before fetching and rendering.
Optional renderMarginPercent
renderMarginPercent ?: numberUsed in conjunction with fetchMarginPercent , this setting allows for prefetching an ad, but waiting to render and download other subresources. As such, this value should always be less than or equal to fetchMarginPercent .
A value of
0 means "when the slot enters the viewport", 100 means "when the ad is 1 viewport away", and so on. googletag.config.PageSettingsConfig
Allows setting multiple features with a single API call.
All properties listed below are examples and do not reflect actual features that utilize setConfig. For the set of features, see fields within the PageSettingsConfig type below.
Примеры:
- Only features specified in the googletag.setConfig call are modified.
// Configure feature alpha. googletag.setConfig({ alpha: {...} }); // Configure feature bravo. Feature alpha is unchanged. googletag.setConfig({ bravo: {...} });
- All settings for a given feature are updated with each call to 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 } });
- All settings for a feature can be cleared by passing
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, });
| Характеристики | |
|---|---|
ad Expansion ? | Settings to control ad expansion. |
adsense Attributes ? | Setting to configure AdSense attributes. |
ad Yield ? | Deprecated. |
category Exclusion ? | Setting to configure ad category exclusions. |
centering ? | Setting to control the horizontal centering of ads. |
collapse Div ? | Setting to control the collapsing behavior of ad slots. |
disable Initial Load ? | Setting to control when ads are requested. |
lazy Load ? | Settings to control the use of lazy loading in GPT. |
location ? | Setting to geo-target line items to geographic locations. |
pps ? | Settings to control publisher provided signals (PPS). |
privacy Treatments ? | Settings to control publisher privacy treatments. |
safe Frame ? | Settings to control the use of SafeFrame in GPT. |
single Request ? | Setting to enable or disable Single Request Architecture (SRA). |
targeting ? | Setting to control key-value targeting. |
thread Yield ? | Setting to control whether GPT should yield the JS thread when requesting and rendering creatives. |
video Ads ? | Settings to control video ads. |
Характеристики
Optional adExpansion
adExpansion ?: AdExpansionConfig Optional adsenseAttributes
adsenseAttributes ?: AdSenseAttributesConfigAdSense attributes configured via this setting will apply to all ad slots on the page. This setting may be called multiple times to define multiple attribute values, or overwrite existing values.
AdSense attribute changes only apply to ads requested after this method has been called. For that reason, it is recommended to call this method before any calls to googletag.display or PubAdsService.refresh .
- Пример
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 (legacy)
// 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 });
Машинопись
// 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 []- Пример
JavaScript
// Label = AirlineAd. googletag.setConfig({ categoryExclusion: ["AirlineAd"] }); // Clearing category exclusion setting. googletag.setConfig({ categoryExclusion: null });
JavaScript (legacy)
// Label = AirlineAd. googletag.setConfig({ categoryExclusion: ["AirlineAd"] }); // Clearing category exclusion setting. googletag.setConfig({ categoryExclusion: null });
Машинопись
// Label = AirlineAd. googletag.setConfig({ categoryExclusion: ["AirlineAd"] }); // Clearing category exclusion setting. googletag.setConfig({ categoryExclusion: null });
- См. также
Optional centering
centering ?: booleanHorizontal centering changes only apply to ads requested after this method has been called. For that reason, it is recommended to call this method before any calls to googletag.display or PubAdsService.refresh .
- Пример
JavaScript
// Make ads centered. googletag.setConfig({ centering: true }); // Clear the centering setting. googletag.setConfig({ centering: null });
JavaScript (legacy)
// Make ads centered. googletag.setConfig({ centering: true }); // Clear the centering setting. googletag.setConfig({ centering: null });
Машинопись
// Make ads centered. googletag.setConfig({ centering: true }); // Clear the centering setting. googletag.setConfig({ centering: null });
Optional collapseDiv
collapseDiv ?: CollapseDivBehaviorA collapsed ad slot does not take up any space on the page.
Supported values:
-
null(default): The slot will not be collapsed. -
DISABLED: The slot will not collapse, whether or not an ad is returned. -
BEFORE_FETCH: The slot will start out collapsed, and expand when an ad is returned. -
ON_NO_FILL: The slot will start out expanded, and collapse if no ad is returned.
- Пример
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 (legacy)
// 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 });
Машинопись
// 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 ?: booleanBy default, the googletag.display method both registers ad slots and requests ads for them. However, there are times when it may be preferable to separate these actions, in order to more precisely control when ad content is loaded.
By enabling this setting, ads will not be requested for registered slots when the
display() method is called. Instead, a separate call to PubAdsService.refresh must be made to initiate an ad request.This method must be called before calling googletag.enableServices .
- Пример
JavaScript
// Prevent requesting ads when `display()` is called. googletag.setConfig({ disableInitialLoad: true });
JavaScript (legacy)
// Prevent requesting ads when `display()` is called. googletag.setConfig({ disableInitialLoad: true });
Машинопись
// Prevent requesting ads when `display()` is called. googletag.setConfig({ disableInitialLoad: true });
Optional lazyLoad
lazyLoad ?: LazyLoadConfigLazy loading is a technique to delay the requesting and rendering of ads until they approach the user's viewport. For a more detailed example, see the Lazy loading sample.
Note: If
singleRequest is enabled, lazy fetching only works when all slots are outside the fetch margin.Any lazy load settings which are not specified when calling
setConfig() will use a default value set by Google. These defaults may be tuned over time. To disable a particular setting, set the value to null .- Пример
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 (legacy)
// 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 });
Машинопись
// 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 location
location ?: string- Пример
JavaScript
// Geo-target line items to US postal code 10001. googletag.setConfig({ location: "10001,US" }); // Clear the location setting. googletag.setConfig({ location: null });
JavaScript (legacy)
// Geo-target line items to US postal code 10001. googletag.setConfig({ location: "10001,US" }); // Clear the location setting. googletag.setConfig({ location: null });
Машинопись
// Geo-target line items to US postal code 10001. googletag.setConfig({ location: "10001,US" }); // Clear the location setting. googletag.setConfig({ location: null });
- См. также
Optional pps
Optional privacyTreatments
privacyTreatments ?: PrivacyTreatmentsConfig Optional safeFrame
safeFrame ?: SafeFrameConfigValues configured via this setting will apply to all ad slots on the page. Individual ad slots may override these values via SlotSettingsConfig.safeFrame .
- Пример
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 (legacy)
// 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 });
Машинопись
// 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 ?: booleanWhen SRA is enabled, all ad slots defined prior to a googletag.display or PubAdsService.refresh call will be batched into a single ad request. This provides performance benefits, but is also necessary to ensure roadblocks and competetive exclusions are honored.
When SRA is disabled, each ad slot is requested individually. This is the default behavior of GPT.
This method must be called prior to calling googletag.enableServices .
- Пример
JavaScript
// Enable Single Request Architecture. googletag.setConfig({ singleRequest: true });
JavaScript (legacy)
// Enable Single Request Architecture. googletag.setConfig({ singleRequest: true });
Машинопись
// Enable Single Request Architecture. googletag.setConfig({ singleRequest: true });
Optional targeting
targeting ?: Record < string , string | string [] >Targeting configured via this setting will apply to all ad slots on the page. This setting may be called multiple times to define multiple targeting key-values, or overwrite existing values. Targeting keys are defined in your Google Ad Manager account.
- Пример
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 (legacy)
// 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 } });
Машинопись
// 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 } });
- См. также
Optional threadYield
threadYield ?: "DISABLED" | "ENABLED_ALL_SLOTS"GPT will yield only for browsers that support the Scheduler.postTask or Scheduler.yield API.
Supported values:
-
null(default): GPT will yield the JS thread for slots outside of the viewport. -
ENABLED_ALL_SLOTS: GPT will yield the JS thread for all slots regardless of whether the slot is within the viewport. -
DISABLED: GPT will not yield the JS thread.
- Пример
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 (legacy)
// 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 });
Машинопись
// 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 });
- См. также
Optional videoAds
videoAds ?: VideoAdsConfig- Пример
JavaScript
// Enable video ads and set video content and content source IDs. googletag.setConfig({ videoAds: { enableVideoAds: true, videoContentId: "e1eGlRL7ju8", videoCmsId: "1234567", }, });
JavaScript (legacy)
// Enable video ads and set video content and content source IDs. googletag.setConfig({ videoAds: { enableVideoAds: true, videoContentId: "e1eGlRL7ju8", videoCmsId: "1234567", }, });
Машинопись
// Enable video ads and set video content and content source IDs. googletag.setConfig({ videoAds: { enableVideoAds: true, videoContentId: "e1eGlRL7ju8", videoCmsId: "1234567", }, });
- См. также
googletag.config.PrivacyTreatmentsConfig
| Характеристики | |
|---|---|
treatments | An array of publisher privacy treatments to enable. |
Характеристики
лечение
treatments : "disablePersonalization" []- Пример
JavaScript
// Disable personalization across the entire page. googletag.setConfig({ privacyTreatments: { treatments: ["disablePersonalization"] }, });
JavaScript (legacy)
// Disable personalization across the entire page. googletag.setConfig({ privacyTreatments: { treatments: ["disablePersonalization"] }, });
Машинопись
// Disable personalization across the entire page. googletag.setConfig({ privacyTreatments: { treatments: ["disablePersonalization"] }, });
googletag.config.PublisherProvidedSignalsConfig
| Характеристики | |
|---|---|
taxonomies | An object containing Taxonomy mappings or null to clear the config. |
- Пример
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 (legacy)
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' }, }, });
Машинопись
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' }, }, });
Характеристики
taxonomies
taxonomies : Partial < Record < Taxonomy , TaxonomyData > >googletag.config.SafeFrameConfig
| Характеристики | |
|---|---|
allow Overlay Expansion ? | Whether SafeFrame should allow ad content to expand by overlaying page content. |
allow Push Expansion ? | Whether SafeFrame should allow ad content to expand by pushing page content. |
force Safe Frame ? | Whether ad(s) should be forced to be rendered using a SafeFrame container. |
sandbox ? | Whether SafeFrame should use the HTML5 sandbox attribute to prevent top level navigation without user interaction. |
use Unique Domain ? | Deprecated. Whether SafeFrame should use randomized subdomains for Reservation creatives. |
Характеристики
Optional allowOverlayExpansion
allowOverlayExpansion ?: boolean Optional allowPushExpansion
allowPushExpansion ?: boolean Optional forceSafeFrame
forceSafeFrame ?: boolean Optional sandbox
sandbox ?: booleantrue (cannot be forced to false ). Note that the sandbox attribute disables plugins (eg Flash). Optional useUniqueDomain
useUniqueDomain ?: booleannull to clear the stored value.Note: this feature is enabled by default.
- См. также
googletag.config.SlotSettingsConfig
Allows setting multiple features with a single API call for a single slot.
All properties listed below are examples and do not reflect actual features that utilize setConfig. For the set of features, see fields within the SlotSettingsConfig type below.
Примеры:
- Only features specified in the Slot.setConfig call are modified.
const slot = googletag.defineSlot("/1234567/example", [160, 600]); // Configure feature alpha. slot.setConfig({ alpha: {...} }); // Configure feature bravo. Feature alpha is unchanged. slot.setConfig({ bravo: {...} });
- All settings for a given feature are updated with each call to 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 } });
- All settings for a feature can be cleared by passing
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, });
| Характеристики | |
|---|---|
ad Expansion ? | Settings to configure ad expansion. |
adsense Attributes ? | Setting to configure AdSense attributes. |
category Exclusion ? | Setting to configure ad category exclusions. |
click Url ? | Setting to configure the URL to which users will be redirected after clicking on the ad. |
collapse Div ? | Setting to configure the collapsing behavior of the ad slot. |
component Auction ? | An array of component auctions to be included in an on-device ad auction. |
interstitial ? | Settings that configure interstitial ad slot behavior. |
safe Frame ? | Settings to configure the use of SafeFrame in GPT. |
targeting ? | Setting to configure key-value targeting. |
Характеристики
Optional adExpansion
adExpansion ?: AdExpansionConfig- См. также
Optional adsenseAttributes
adsenseAttributes ?: AdSenseAttributesConfigAdSense attributes configured via this setting will only apply to the ad slot. This setting may be called multiple times to define multiple attribute values, or overwrite existing values.
AdSense attribute changes only apply to ads requested after this method has been called. For that reason, it is recommended to call this method before any calls to googletag.display or PubAdsService.refresh .
- Пример
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 (legacy)
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 });
Машинопись
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 []- Пример
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 (legacy)
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 });
Машинопись
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 });
- См. также
Optional clickUrl
clickUrl ?: stringThe Google Ad Manager servers still record a click even if the click URL is replaced. Any landing page URL associated with the creative that is served is appended to the provided value. Setting this value more than once will overwrite any previously configured value. Passing in
null will clear the value.Note: This setting only applies to non-SRA requests .
- Пример
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 (legacy)
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, });
Машинопись
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 ?: CollapseDivBehaviorA collapsed ad slot does not take up any space on the page.
Supported values:
-
null(default): The slot will not be collapsed. -
DISABLED: The slot will not collapse, whether or not an ad is returned. -
BEFORE_FETCH: The slot will start out collapsed, and expand when an ad is returned. -
ON_NO_FILL: The slot will start out expanded, and collapse if no ad is returned.
- Пример
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 (legacy)
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, });
Машинопись
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- См. также
Optional safeFrame
safeFrame ?: SafeFrameConfigValues configured via this setting will only apply to the ad slot, and override values set via PageSettingsConfig.safeFrame .
- Пример
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 (legacy)
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 });
Машинопись
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 targeting
targeting ?: Record < string , string | string [] >Targeting configured via this setting will only apply to the ad slot. This setting may be called multiple times to define multiple targeting key-values, or overwrite existing values. Targeting keys are defined in your Google Ad Manager account.
- Пример
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 (legacy)
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 });
Машинопись
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 });
- См. также
googletag.config.TaxonomyData
| Характеристики | |
|---|---|
values | A list of Taxonomy values. |
Характеристики
ценности
values : readonly string []googletag.config.VideoAdsConfig
| Характеристики | |
|---|---|
enable Video Ads | Whether videos ads will be present on the page. |
video Cms Id ? | The video content source ID. |
video Content Id ? | The video content ID. |
- См. также
Характеристики
enableVideoAds
enableVideoAds : booleanWhen set to
true , this enables content exclusion constraints on display and video ads.If the video content is known, set videoContentId and videoCmsId to the values provided to the Google Ad Manager content ingestion service to utilize content exclusion for display ads.
Optional videoCmsId
videoCmsId ?: stringThis is a unique value assigned by the Google Ad Manager content ingestion service to identify the source of video content specified by videoContentId .
- См. также
Optional videoContentId
videoContentId ?: stringThis is a unique value that identifies a particular video from the content source specified by videoCmsId . This value is assigned by the CMS that hosts your video content.
- См. также
googletag.enums
| Перечисления | |
|---|---|
Out Of Page Format | Out-of-page formats supported by GPT. |
Traffic Source | Traffic sources supported by GPT. |
Перечисления
OutOfPageFormat
OutOfPageFormat- См. также
TrafficSource
TrafficSource- См. также
| Enumeration Members | |
|---|---|
ORGANIC | Direct URL entry, site search, or app download. |
PURCHASED | Traffic redirected from properties other than owned (acquired or otherwise incentivized activity). |
googletag.events
| Интерфейсы | |
|---|---|
Event | Base Interface for all GPT events. |
Event Type Map | This is a pseudo-type that maps an event name to its corresponding event object type for Service.addEventListener and Service.removeEventListener . |
Game Manual Interstitial Slot Closed Event | This event is fired when a game manual interstitial slot has been closed by the user. |
Game Manual Interstitial Slot Ready Event | This event is fired when a game manual interstitial slot is ready to be shown to the user. |
Impression Viewable Event | This event is fired when an impression becomes viewable, according to the Active View criteria . |
Rewarded Slot Closed Event | This event is fired when a rewarded ad slot is closed by the user. |
Rewarded Slot Granted Event | This event is fired when a reward is granted for viewing a rewarded ad . |
Rewarded Slot Ready Event | This event is fired when a rewarded ad is ready to be displayed. |
Rewarded Slot Video Completed Event | This event is fired when a rewarded video ad has finished playing. |
Slot Onload Event | This event is fired when the creative's iframe fires its load event. |
Slot Render Ended Event | This event is fired when the creative code is injected into a slot. |
Slot Requested Event | This event is fired when an ad has been requested for a particular slot. |
Slot Response Received | This event is fired when an ad response has been received for a particular slot. |
Slot Visibility Changed Event | This event is fired whenever the on-screen percentage of an ad slot's area changes. |
googletag.events.Event
| Характеристики | |
|---|---|
service Name | Name of the service that triggered the event. |
slot | The slot that triggered the event. |
- См. также
Характеристики
serviceName
serviceName : stringслот
slot : Slotgoogletag.events.EventTypeMap
| Характеристики | |
|---|---|
game Manual Interstitial Slot Closed | Alias for events.GameManualInterstitialSlotClosedEvent . |
game Manual Interstitial Slot Ready | Alias for events.GameManualInterstitialSlotReadyEvent . |
impression Viewable | Alias for events.ImpressionViewableEvent . |
rewarded Slot Closed | Alias for events.RewardedSlotClosedEvent . |
rewarded Slot Granted | Alias for events.RewardedSlotGrantedEvent . |
rewarded Slot Ready | Alias for events.RewardedSlotReadyEvent . |
rewarded Slot Video Completed | Alias for events.RewardedSlotVideoCompletedEvent . |
slot Onload | Alias for events.SlotOnloadEvent . |
slot Render Ended | Alias for events.SlotRenderEndedEvent . |
slot Requested | Alias for events.SlotRequestedEvent . |
slot Response Received | Alias for events.SlotResponseReceived . |
slot Visibility Changed | Alias for events.SlotVisibilityChangedEvent . |
Характеристики
gameManualInterstitialSlotClosed
gameManualInterstitialSlotClosed : GameManualInterstitialSlotClosedEventgameManualInterstitialSlotReady
gameManualInterstitialSlotReady : GameManualInterstitialSlotReadyEventimpressionViewable
impressionViewable : ImpressionViewableEventrewardedSlotClosed
rewardedSlotClosed : RewardedSlotClosedEventrewardedSlotGranted
rewardedSlotGranted : RewardedSlotGrantedEventrewardedSlotReady
rewardedSlotReady : RewardedSlotReadyEventrewardedSlotVideoCompleted
rewardedSlotVideoCompleted : RewardedSlotVideoCompletedEventslotOnload
slotOnload : SlotOnloadEventslotRenderEnded
slotRenderEnded : SlotRenderEndedEventslotRequested
slotRequested : SlotRequestedEventslotResponseReceived
slotResponseReceived : SlotResponseReceivedslotVisibilityChanged
slotVisibilityChanged : SlotVisibilityChangedEventgoogletag.events.GameManualInterstitialSlotClosedEvent
EventNote: Game manual interstitial is a limited-access format.
| Характеристики | |
|---|---|
service Name | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Пример
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 (legacy)
// 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. } }); }
Машинопись
// 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
EventNote: Game manual interstitial is a limited-access format.
| Характеристики | |
|---|---|
service Name | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
| Методы | |
|---|---|
make Game Manual Interstitial Visible | Displays the game manual interstitial ad to the user. |
- Пример
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 (legacy)
// 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. } }); }
Машинопись
// 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. } }); }
Методы
makeGameManualInterstitialVisible
makeGameManualInterstitialVisible ( ) : boolean| Возвраты | |
|---|---|
boolean | |
googletag.events.ImpressionViewableEvent
Event| Характеристики | |
|---|---|
service Name | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Пример
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 (legacy)
// 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. } });
Машинопись
// 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. } });
- См. также
googletag.events.RewardedSlotClosedEvent
Event| Характеристики | |
|---|---|
service Name | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Пример
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 (legacy)
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. } }); }
Машинопись
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
Event| Характеристики | |
|---|---|
payload | An object containing information about the reward that was granted. |
service Name | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Пример
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 (legacy)
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. } }); }
Машинопись
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. } }); }
- См. также
Характеристики
полезная нагрузка
payload : RewardedPayloadgoogletag.events.RewardedSlotReadyEvent
Event| Характеристики | |
|---|---|
service Name | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
| Методы | |
|---|---|
make Rewarded Visible | Displays the rewarded ad. |
- Пример
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 (legacy)
// 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. } }); }
Машинопись
// 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. } }); }
- См. также
Методы
makeRewardedVisible
makeRewardedVisible ( ) : boolean| Возвраты | |
|---|---|
boolean | Whether the rewarded ad was successfully displayed. |
googletag.events.RewardedSlotVideoCompletedEvent
Event| Характеристики | |
|---|---|
service Name | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Пример
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 (legacy)
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. } }); }
Машинопись
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
EventSlotOnloadEvent will be fired. | Характеристики | |
|---|---|
service Name | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Пример
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 (legacy)
// 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. } });
Машинопись
// 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. } });
- См. также
googletag.events.SlotRenderEndedEvent
Event| Характеристики | |
|---|---|
advertiser Id | Advertiser ID of the rendered ad. |
campaign Id | Campaign ID of the rendered ad. |
company Ids | IDs of the companies that bid on the rendered backfill ad. |
creative Id | Creative ID of the rendered reservation ad. |
creative Template Id | Creative template ID of the rendered reservation ad. |
is Backfill | Whether an ad was a backfill ad. |
is Empty | Whether an ad was returned for the slot. |
label Ids | Deprecated. |
line Item Id | Line item ID of the rendered reservation ad. |
response Identifier | The response identifier is a unique identifier for the ad response. |
service Name | Name of the service that triggered the event. Inherited from |
size | Indicates the pixel size of the rendered creative. |
slot | The slot that triggered the event. Inherited from |
slot Content Changed | Whether the slot content was changed with the rendered ad. |
source Agnostic Creative Id | Creative ID of the rendered reservation or backfill ad. |
source Agnostic Line Item Id | Line item ID of the rendered reservation or backfill ad. |
yield Group Ids | IDs of the yield groups for the rendered backfill ad. |
- Пример
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 (legacy)
// 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. } });
Машинопись
// 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. } });
- См. также
Характеристики
advertiserId
advertiserId : numbernull for empty slots, backfill ads, and creatives rendered by services other than PubAdsService . campaignId
campaignId : numbernull for empty slots, backfill ads, and creatives rendered by services other than PubAdsService . companyIds
companyIds : number []null for empty slots, reservation ads, and creatives rendered by services other than PubAdsService . creativeId
creativeId : numbernull for empty slots, backfill ads, and creatives rendered by services other than PubAdsService . creativeTemplateId
creativeTemplateId : numbernull for empty slots, backfill ads, and creatives rendered by services other than PubAdsService . isBackfill
isBackfill : booleantrue if the ad was a backfill ad, false otherwise. isEmpty
isEmpty : booleantrue if no ad was returned, false otherwise. labelIds
labelIds : number []lineItemId
lineItemId : numbernull for empty slots, backfill ads, and creatives rendered by services other than PubAdsService . responseIdentifier
responseIdentifier : stringразмер
size : string | number [][728, 90] . Value is null for empty ad slots. slotContentChanged
slotContentChanged : booleantrue if the content was changed, false otherwise. sourceAgnosticCreativeId
sourceAgnosticCreativeId : numbernull if the ad is not a reservation or line item backfill, or the creative is rendered by services other than PubAdsService . sourceAgnosticLineItemId
sourceAgnosticLineItemId : numbernull if the ad is not a reservation or line item backfill, or the creative is rendered by services other than PubAdsService . yieldGroupIds
yieldGroupIds : number []null for empty slots, reservation ads, and creatives rendered by services other than PubAdsService . googletag.events.SlotRequestedEvent
Event| Характеристики | |
|---|---|
service Name | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Пример
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 (legacy)
// 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. } });
Машинопись
// 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. } });
- См. также
googletag.events.SlotResponseReceived
Event| Характеристики | |
|---|---|
service Name | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Пример
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 (legacy)
// 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. } });
Машинопись
// 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. } });
- См. также
googletag.events.SlotVisibilityChangedEvent
Event| Характеристики | |
|---|---|
in View Percentage | The percentage of the ad's area that is visible. |
service Name | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Пример
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 (legacy)
// 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. } });
Машинопись
// 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. } });
- См. также
Характеристики
inViewPercentage
inViewPercentage : numbergoogletag.secureSignals
| Интерфейсы | |
|---|---|
Bidder Signal Provider | Returns a secure signal for a specific bidder. |
Publisher Signal Provider | Returns a secure signal for a specific publisher. |
Secure Signal Providers Array | An interface for managing secure signals. |
| Псевдонимы типов | |
|---|---|
Secure Signal Provider | Interface for returning a secure signal for a specific bidder or provider. |
Псевдонимы типов
SecureSignalProvider
SecureSignalProvider : BidderSignalProvider | PublisherSignalProviderid or networkCode must be provided, but not both. googletag.secureSignals.BidderSignalProvider
A bidder secure signal provider consists of 2 parts:
- A collector function, which returns a
Promisethat resolves to a secure signal. - An
idwhich identifies the bidder associated with the signal.
| Характеристики | |
|---|---|
collector Function | A function which returns a Promise that resolves to a secure signal. |
id | A unique identifier for the collector associated with this secure signal, as registered in Google Ad Manager. |
- Пример
JavaScript
// id is provided googletag.secureSignalProviders.push({ id: "collector123", collectorFunction: () => { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
JavaScript (legacy)
// id is provided googletag.secureSignalProviders.push({ id: "collector123", collectorFunction: function () { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
Машинопись
// id is provided googletag.secureSignalProviders!.push({ id: "collector123", collectorFunction: () => { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
- См. также
Характеристики
collectorFunction
collectorFunction : ( ( ) => Promise < string > )Promise that resolves to a secure signal. идентификатор
id : stringgoogletag.secureSignals.PublisherSignalProvider
A publisher signal provider consists of 2 parts:
- A collector function, which returns a
Promisethat resolves to a secure signal. - A
networkCodewhich identifies the publisher associated with the signal.
| Характеристики | |
|---|---|
collector Function | A function which returns a Promise that resolves to a secure signal. |
network Code | The network code (as seen in the ad unit path) for the publisher associated with this secure signal. |
- Пример
JavaScript
// networkCode is provided googletag.secureSignalProviders.push({ networkCode: "123456", collectorFunction: () => { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
JavaScript (legacy)
// networkCode is provided googletag.secureSignalProviders.push({ networkCode: "123456", collectorFunction: function () { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
Машинопись
// networkCode is provided googletag.secureSignalProviders!.push({ networkCode: "123456", collectorFunction: () => { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
- См. также
Характеристики
collectorFunction
collectorFunction : ( ( ) => Promise < string > )Promise that resolves to a secure signal. networkCode
networkCode : stringgoogletag.secureSignals.SecureSignalProvidersArray
| Методы | |
|---|---|
clear All Cache | Clears all signals for all collectors from cache. |
push | Adds a new secureSignals.SecureSignalProvider to the signal provider array and begins the signal generation process. |
Методы
clearAllCache
clearAllCache ( ) : voidCalling this method may reduce the likelihood of signals being included in ad requests for the current and potentially later page views. Due to this, it should only be called when meaningful state changes occur, such as events that indicate a new user (log in, log out, sign up, etc.).
толкать
push ( provider : SecureSignalProvider ) : void| Параметры | |
|---|---|
provider : SecureSignalProvider | The secureSignals.SecureSignalProvider object to be added to the array. |