Справочник GPT

В этом справочнике для описания типов используется нотация 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 — это остаточный параметр , принимающий функции. Остаточные параметры принимают неограниченное количество значений указанного типа.

Googleтег

Глобальное пространство имен, которое Google Publisher Tag использует для своего API.
Пространства имен
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
Слот — объект, представляющий собой одно рекламное место на странице.
Псевдонимы типов
General Size
Допустимая конфигурация размера слота, которая может быть одного или нескольких размеров.
Multi Size
Список единственно допустимых размеров.
Named Size
Именованные размеры, которые может иметь слот.
Single Size
Единый допустимый размер для слота.
Single Size Array
Массив из двух чисел, представляющих [ширину, высоту].
Size Mapping
Сопоставление размера области просмотра с размерами рекламы.
Size Mapping Array
Список сопоставлений размеров.
Переменные
api Ready
Флаг, указывающий, что GPT API загружен и готов к вызову.
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 Publisher Console.
display
Дает указание слот-сервисам отобразить слот.
enable Services
Включает все службы GPT, определенные для рекламных мест на странице.
get Config
Получает общие параметры конфигурации для страницы, заданные setConfig .
get Version
Возвращает текущую версию GPT.
open Console
Открывает консоль издателя Google.
pubads
Возвращает ссылку на PubAdsService .
set Ad Iframe Title
Задает заголовок для всех фреймов контейнеров рекламы, создаваемых PubAdsService , начиная с этого момента.
set Config
Устанавливает общие параметры конфигурации страницы.
size Mapping
Создает новый SizeMappingBuilder .

Псевдонимы типов


GeneralSize

GeneralSize : SingleSize | MultiSize
Допустимая конфигурация размера слота, которая может быть одного или нескольких размеров.

Мультиразмер

MultiSize : SingleSize []
Список единственно допустимых размеров.

NamedSize

NamedSize : "fluid" | [ "fluid" ]
Именованные размеры, которые может иметь слот. В большинстве случаев размер — это прямоугольник фиксированного размера, но в некоторых случаях требуются другие типы размеров. Допустимы только следующие именованные размеры:
  • «Резина »: контейнер рекламы занимает 100% ширины родительского блока div, а затем изменяет его высоту в соответствии с креативным контентом. Аналогично тому, как ведут себя обычные блочные элементы на странице. Используется для нативной рекламы (см. соответствующую статью ). Обратите внимание, что оба fluid и ['fluid'] являются допустимыми для объявления размера слота как «резинового».

SingleSize

SingleSize : SingleSizeArray | NamedSize
Единый допустимый размер для слота.

SingleSizeArray

SingleSizeArray : [ number , number ]
Массив из двух чисел, представляющих [ширину, высоту].

SizeMapping

SizeMapping : [ SingleSizeArray , GeneralSize ]
Сопоставление размера области просмотра с размерами рекламного объявления. Используется для адаптивной рекламы.

SizeMappingArray

SizeMappingArray : SizeMapping []
Список сопоставлений размеров.

Переменные


Const apiReady

apiReady : boolean | undefined
Флаг, указывающий, что API GPT загружен и готов к вызову. Это свойство будет просто undefined пока API не будет готов.

Обратите внимание, что рекомендуемый способ обработки асинхронности — использовать googletag.cmd для постановки обратных вызовов в очередь, когда GPT будет готов. Эти обратные вызовы не обязательно должны проверять googletag.apiReady, поскольку они гарантированно выполняются после настройки API.

Const команда

cmd : ( ( this : typeof globalThis ) => void ) [] | CommandArray
Ссылка на глобальную очередь команд для асинхронного выполнения вызовов, связанных с GPT.

Переменная 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 | undefined
Флаг, указывающий, что PubAdsService включён, загружен и полностью работоспособен. Это свойство будет просто undefined до тех пор, пока не будет вызван метод 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 .
Возврат
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 Полный путь к рекламному блоку с кодом сети и кодом рекламного блока.
Optional div : string | OutOfPageFormat Идентификатор div, который будет содержать этот рекламный блок или OutOfPageFormat.
Возврат
Slot | null Вновь созданный слот или null , если слот не может быть создан.

defineSlot

defineSlot ( adUnitPath : string , size : GeneralSize , div ?: string ) : Slot | null
Создает рекламный слот с заданным путем и размером рекламного блока и связывает его с идентификатором элемента div на странице, которая будет содержать рекламу.
Пример

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 Ширина и высота добавленного слота. Этот размер используется в запросе объявления, если адаптивное сопоставление размеров не предусмотрено или размер области просмотра меньше минимального размера, указанного в сопоставлении.
Optional div : string Идентификатор div, который будет содержать этот рекламный блок.
Возврат
Slot | null Вновь созданный слот или null , если слот не может быть создан.

уничтожитьСлоты

destroySlots ( slots ?: Slot [] ) : boolean
Уничтожает заданные слоты, удаляя все связанные объекты и ссылки на эти слоты из GPT. Этот API не поддерживает слоты обратного доступа и сопутствующие слоты.

Вызов этого 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();
Параметры
Optional slots : Slot [] Массив слотов для удаления. Массив необязателен; если он не указан, все слоты будут удалены.
Возврат
boolean true если слоты были уничтожены, в противном случае false .

отключить PublisherConsole

disablePublisherConsole ( ) : void
Отключает Google Publisher Console.
Смотрите также

отображать

display ( divOrSlot : string | Element | Slot ) : void
Указывает сервисам слотов отобразить слот. Каждый рекламный слот должен отображаться только один раз на странице. Все слоты должны быть определены и с ними должна быть связана служба до их отображения. Вызов метода display не должен выполняться, пока элемент не появится в DOM. Обычно это достигается размещением его в блоке скрипта внутри элемента div, указанного в вызове метода.

При использовании архитектуры единого запроса (SRA) все неизвлеченные на момент вызова этого метода рекламные места будут извлечены одновременно. Чтобы рекламное место не отображалось, необходимо удалить весь блок div.
Смотрите также
Параметры
divOrSlot : string | Element | Slot Либо идентификатор элемента div, содержащего рекламное место, либо сам элемент div, либо объект слота. Если указан элемент div, он должен иметь атрибут id, соответствующий идентификатору, переданному в defineSlot .

enableServices

enableServices ( ) : void
Включает все службы GPT, определенные для рекламных мест на странице.

получитьConfig

getConfig ( keys : string | string [] ) : Pick < PageSettingsConfig , "adsenseAttributes" | "disableInitialLoad" | "targeting" >
Получает общие параметры конфигурации для страницы, заданные setConfig .

Этот метод поддерживает не все свойства 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
Возвращает текущую версию GPT.
Смотрите также
Возврат
string Строка текущей исполняемой версии GPT.

openConsole

openConsole ( div ?: string ) : void
Открывает консоль издателя Google.
Пример

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();
Смотрите также
Параметры
Optional div : string Идентификатор div рекламного места. Это значение необязательно. При его указании консоль издателя попытается открыть его, отобразив сведения об указанном рекламном месте.

пабы

pubads ( ) : PubAdsService
Возвращает ссылку на PubAdsService .
Возврат
PubAdsService Служба рекламы издателей.

setAdIframeTitle

setAdIframeTitle ( title : string ) : void
Задает заголовок для всех фреймов контейнеров рекламы, создаваемых PubAdsService , начиная с этого момента.
Пример

JavaScript

googletag.setAdIframeTitle("title");

JavaScript (устаревший)

googletag.setAdIframeTitle("title");

Машинопись

googletag.setAdIframeTitle("title");
Параметры
title : string Новый заголовок для всех фреймов рекламного контейнера.

setConfig

setConfig ( config : PageSettingsConfig ) : void
Устанавливает общие параметры конфигурации страницы.
Параметры
config : PageSettingsConfig

sizeMapping

sizeMapping ( ) : SizeMappingBuilder
Создает новый SizeMappingBuilder .
Смотрите также
Возврат
SizeMappingBuilder Новый застройщик.

googletag.CommandArray

Массив команд принимает последовательность функций и вызывает их по порядку. Он предназначен для замены стандартного массива, используемого для постановки функций в очередь на вызов после загрузки GPT.
Методы
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());
});
Параметры
Rest ... f : ( ( this : typeof globalThis ) => void ) [] Функция 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 ?: boolean
Указывает, следует ли рассматривать страницу как предназначенную для детей . Установите значение null чтобы очистить конфигурацию.

Optional ограниченная реклама

limitedAds ?: boolean
Позволяет запускать показ рекламы в режиме ограниченной рекламы , чтобы помочь издателям соблюдать нормативные требования.

Вы можете указать GPT запрашивать ограниченный показ рекламы двумя способами:
  • Автоматически, используя сигнал от платформы управления согласием IAB TCF v2.0 .
  • Вручную, установив значение этого поля на true .
Ручная настройка ограниченного показа рекламы возможна только при загрузке GPT с URL-адреса ограниченной рекламы . Попытка изменить этот параметр при загрузке GPT со стандартного URL-адреса приведёт к появлению предупреждения в консоли издателя .

Обратите внимание, что при использовании 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 ?: boolean
Позволяет запускать обслуживание в режиме ограниченной обработки , чтобы помочь издателям соблюдать нормативные требования.

Optional источник трафика

trafficSource ?: TrafficSource
Указывает, представляют ли запросы купленный или органический трафик. Это значение используется в параметре «Источник трафика» в отчётах Менеджера рекламы. Если значение не задано, в отчётах источник трафика по умолчанию считается undefined .
Пример

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 ?: boolean
Указывает, следует ли отмечать запросы на рекламу как поступающие от пользователей, не достигших возраста согласия . Установите значение null чтобы очистить конфигурацию.

googletag.PubAdsService

Расширяет Service
Сервис Publisher Ads. Этот сервис используется для получения и показа рекламы из вашего аккаунта Google Ad Manager.
Методы
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();
Параметры
Optional slots : Slot [] Массив слотов для очистки. Массив необязателен; если он не указан, все слоты будут очищены.
Возврат
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.
Смотрите также
Параметры
Optional key : string Ключ параметра таргетинга. Этот ключ необязателен; все параметры таргетинга будут удалены, если он не указан.
Возврат
PubAdsService Объект службы, для которого был вызван метод.

свернутьEmptyDivs

collapseEmptyDivs ( collapseBeforeAdFetch ?: boolean ) : boolean
Позволяет сворачивать div-блоки, чтобы они не занимали место на странице, когда на них нет рекламного контента. Этот режим необходимо включить до включения сервиса.
Смотрите также
Параметры
Optional collapseBeforeAdFetch : boolean Сворачивать ли слоты ещё до загрузки рекламы. Этот параметр необязателен; если не указан, по умолчанию будет использоваться значение false .
Возврат
boolean Возвращает true , если режим свертывания div был включен, и false , если невозможно включить режим свертывания, поскольку метод был вызван после включения службы.

отключить начальную загрузку

disableInitialLoad ( ) : void
Отключает запросы рекламы при загрузке страницы, но разрешает запрашивать рекламу с помощью вызова PubAdsService.refresh . Это необходимо настроить до включения службы. Необходимо использовать асинхронный режим, иначе запрос рекламы с помощью refresh будет невозможен.
Смотрите также

отображать

display ( adUnitPath : string , size : GeneralSize , div ?: string | Element , clickUrl ?: string ) : void
Создаёт и отображает рекламное место с заданным путём и размером рекламного блока. Этот метод не работает в режиме одиночного запроса.

Примечание: При вызове этого метода создаётся снимок состояния слота и страницы для обеспечения согласованности при отправке запроса на рекламу и отображении ответа. Любые изменения состояния слота или страницы после вызова этого метода (включая таргетинг, настройки конфиденциальности, принудительное использование SafeFrame и т. д.) будут применяться только к последующим запросам 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 Ширина и высота прорези.
Optional div : string | Element Либо идентификатор div, содержащего слот, либо сам элемент div.
Optional clickUrl : string URL-адрес клика для использования в этом слоте.

enableLazyLoad

enableLazyLoad ( config ?: {
  fetchMarginPercent ?: number ;
  mobileScaling ?: number ;
  renderMarginPercent ?: number ;
} ) : void
Включает отложенную загрузку в GPT, как определено в объекте конфигурации. Более подробные примеры см. в примере «Отложенная загрузка» .

Примечание: Ленивая выборка в 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,
});
Смотрите также
Параметры
Optional config : {
  fetchMarginPercent ?: number ;
  mobileScaling ?: number ;
  renderMarginPercent ?: number ;
}
Объект конфигурации позволяет настраивать ленивое поведение. Все пропущенные конфигурации будут использовать конфигурацию по умолчанию, установленную Google, которая будет корректироваться со временем. Чтобы отключить определённый параметр, например, поле для выборки, установите значение -1 .
  • fetchMarginPercent

    Минимальное расстояние между слотом и текущей областью просмотра, необходимое для загрузки рекламы, выраженное в процентах от размера области просмотра. Значение 0 означает, что слот попадает в область просмотра, 100 — что реклама находится на расстоянии одной области просмотра и т. д.
  • renderMarginPercent

    Минимальное расстояние от текущей области просмотра до слота, на котором должна отображаться реклама. Это позволяет предварительно загрузить рекламу, не дожидаясь её отрисовки и загрузки других подресурсов. Значение работает аналогично fetchMarginPercent , но в процентах от области просмотра.
  • mobileScaling

    Множитель, применяемый к полям на мобильных устройствах. Это позволяет варьировать поля на мобильных устройствах и компьютерах. Например, значение 2,0 умножит все поля на 2 на мобильных устройствах, увеличивая минимальное расстояние между слотами до загрузки и отрисовки.

enableSingleRequest

enableSingleRequest ( ) : boolean
Включает режим единого запроса для одновременного получения нескольких объявлений. Для этого необходимо определить все слоты Publisher Ads и добавить их в PubAdsService до включения сервиса. Режим единого запроса необходимо настроить до включения сервиса.
Смотрите также
Возврат
boolean Возвращает true , если был включен режим одиночного запроса, и false , если невозможно включить режим одиночного запроса, поскольку метод был вызван после включения службы.

enableVideoAds

enableVideoAds ( ) : void
Сигнализирует GPT о том, что на странице будет видеореклама. Это позволяет накладывать ограничения на конкурентное исключение для медийной и видеорекламы. Если видеоконтент известен, вызовите PubAdsService.setVideoContent , чтобы использовать исключение контента для медийной рекламы.

получать

get ( key : string ) : string
Возвращает значение атрибута AdSense, связанного с заданным ключом.
Пример

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 , если ключ отсутствует.

получитьAttributeKeys

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
Возвращает информацию о том, были ли первоначальные запросы на рекламу успешно отключены предыдущим вызовом PubAdsService.disableInitialLoad .
Возврат
boolean Возвращает true , если предыдущий вызов PubAdsService.disableInitialLoad был успешным, в противном случае — false .

обновить

refresh ( slots ?: Slot [] , options ?: {
  changeCorrelator : boolean ;
} ) : void
Находит и отображает новые объявления для определенных или всех слотов на странице. Работает только в асинхронном режиме рендеринга.

Для корректной работы во всех браузерах вызову refresh должен предшествовать вызов 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 });
Смотрите также
Параметры
Optional slots : Slot [] Слоты для обновления. Массив необязателен; если он не указан, будут обновлены все слоты.
Optional options : {
  changeCorrelator : boolean ;
}
Параметры конфигурации, связанные с этим вызовом обновления.
  • changeCorrelator

    Указывает, следует ли генерировать новый коррелятор для показа рекламы. Наши рекламные серверы сохраняют это значение коррелятора в течение короткого времени (в настоящее время 30 секунд, но это время может измениться), поэтому запросы с одним и тем же коррелятором, полученные близко друг к другу, будут считаться одним просмотром страницы. По умолчанию новый коррелятор генерируется при каждом обновлении.

    Примечание: эта опция не влияет на долгосрочный просмотр страницы GPT, который автоматически отражает рекламу, находящуюся в данный момент на странице, и не имеет срока действия.

набор

set ( key : string , value : string ) : PubAdsService
Задает значения атрибутов AdSense, которые применяются ко всем рекламным местам в службе Publisher Ads.

Повторный вызов этого метода для одного и того же ключа переопределит ранее заданные значения для этого ключа. Все значения должны быть установлены до вызова 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
Включает и отключает горизонтальное центрирование рекламы. По умолчанию центрирование отключено. В устаревшей версии gpt_mobile.js центрирование включено по умолчанию.

Этот метод следует вызывать до вызова 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
Настраивает, следует ли принудительно отображать все рекламные объявления на странице с использованием контейнера SafeFrame.

При использовании этого API помните следующее:
  • Эта настройка вступит в силу только для последующих запросов объявлений, сделанных для соответствующих слотов.
  • Настройка уровня слота, если она указана, всегда переопределяет настройку уровня страницы.
  • Если установлено значение true (на уровне слота или страницы), объявление всегда будет отображаться с использованием контейнера SafeFrame независимо от выбора, сделанного в пользовательском интерфейсе Google Ad Manager.
  • Однако если задано значение false или не указано иное, реклама будет отображаться с использованием контейнера SafeFrame в зависимости от типа креатива и выбора, сделанного в пользовательском интерфейсе Google Ad Manager.
  • Этот API следует использовать с осторожностью, поскольку он может повлиять на поведение креативов, которые пытаются вырваться за пределы своих iFrame или рассчитывают на их прямую визуализацию на странице издателя.
Пример

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. Установка значения 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
Позволяет настраивать все параметры конфиденциальности из одного API с помощью объекта конфигурации.
Пример

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
Задаёт настройки на уровне страницы для конфигурации SafeFrame. Любые нераспознанные ключи в объекте конфигурации будут игнорироваться. Вся конфигурация будет игнорироваться, если для распознанного ключа передано недопустимое значение.

Эти настройки на уровне страницы будут переопределены настройками на уровне слота, если они указаны.
Пример

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
Устанавливает пользовательские параметры таргетинга для заданного ключа, применяемые ко всем рекламным местам сервиса Publisher Ads. Многократный вызов этого метода для одного и того же ключа перезапишет старые значения. Эти ключи определены в вашем аккаунте Google Ad Manager.
Пример

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 ) : void
Задаёт информацию о видеоконтенте, которая будет отправляться вместе с запросами рекламы для таргетинга и исключения контента. Видеореклама будет автоматически включена при вызове этого метода. Для videoContentId и 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 : number
Идентификатор рекламодателя.

идентификатор кампании

campaignId : number
Идентификатор кампании.

creativeId

creativeId : number
Идентификатор креатива.

creativeTemplateId

creativeTemplateId : number
Идентификатор шаблона объявления.

lineItemId

lineItemId : number
Идентификатор позиции.

googletag.RewardedPayload

Объект, представляющий вознаграждение, связанное с объявлением с вознаграждением.
Характеристики
amount
Количество предметов, входящих в награду.
type
Тип предмета, входящего в награду (например, «монета»).
Смотрите также

Характеристики


количество

amount : number
Количество предметов, входящих в награду.

тип

type : string
Тип предмета, входящего в награду (например, «монета»).

googletag.Service

Базовый класс сервиса, содержащий общие для всех сервисов методы.
Методы
add Event Listener
Регистрирует прослушиватель, который позволяет настраивать и вызывать функцию JavaScript при возникновении определенного события GPT на странице.
get Slots
Получите список слотов, связанных с этой услугой.
remove Event Listener
Удаляет ранее зарегистрированного слушателя.

Методы


addEventListener

addEventListener < K extends keyof EventTypeMap > ( eventType : K , listener : ( ( arg : EventTypeMap [ K ] ) => void ) ) : Service
Регистрирует прослушиватель, позволяющий настроить и вызвать функцию JavaScript при возникновении определённого события GPT на странице. Поддерживаются следующие события: При вызове прослушивателю передается объект соответствующего типа события.
Пример

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 (устаревший)

// 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 Строка, представляющая тип события, сгенерированного GPT. Типы событий чувствительны к регистру.
listener : ( ( arg : EventTypeMap [ K ] ) => void ) Функция, которая принимает один аргумент объекта события.
Возврат
Service Объект службы, для которого был вызван метод.

getSlots

getSlots ( ) : Slot []
Получите список слотов, связанных с этой услугой.
Возврат
Slot [] Слоты в том порядке, в котором они были добавлены в сервис.

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 (устаревший)

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 Строка, представляющая тип события, сгенерированного GPT. Типы событий чувствительны к регистру.
listener : ( ( event : EventTypeMap [ K ] ) => void ) Функция, которая принимает один аргумент объекта события.

googletag.SizeMappingBuilder

Builder for size mapping specification objects. This builder is provided to help easily construct size specifications.
Методы
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
Adds a mapping from a single-size array (representing the viewport) to a single- or multi-size array representing the slot.
Пример

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 &lt; 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 (устаревший)

// 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 &lt; 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 &lt; 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 ( ) : SizeMappingArray
Builds a size map specification from the mappings added to this builder.

If 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

Slot is an object representing a single ad slot on a page.
Методы
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
Adds a Service to this slot.
Пример

JavaScript

googletag.defineSlot("/1234567/sports", [160, 600], "div").addService(googletag.pubads());

JavaScript (устаревший)

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
Clears all slot-level ad category exclusion labels for this 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 (устаревший)

// 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
Clears specific or all custom slot-level targeting parameters for this 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 (устаревший)

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.
Смотрите также
Параметры
Optional key : string 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
Sets an array of mappings from a minimum viewport size to slot size for this 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 (устаревший)

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
Returns the value for the AdSense attribute associated with the given key for this slot. To see service-level attributes inherited by this slot, use PubAdsService.get .
Пример

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 (устаревший)

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
Returns the full path of the ad unit, with the network code and ad unit path.
Пример

JavaScript

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .addService(googletag.pubads());

slot.getAdUnitPath();
// Returns '/1234567/sports'.

JavaScript (устаревший)

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 []
Returns the list of attribute keys set on this slot. To see the keys of service-level attributes inherited by this slot, use PubAdsService.getAttributeKeys .
Пример

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 (устаревший)

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 []
Returns the ad category exclusion labels for this slot.
Пример

JavaScript

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setCategoryExclusion("AirlineAd")
  .setCategoryExclusion("TrainAd")
  .addService(googletag.pubads());

slot.getCategoryExclusions();
// Returns ['AirlineAd', 'TrainAd'].

JavaScript (устаревший)

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.

получитьConfig

getConfig ( keys : string | string [] ) : Pick < SlotSettingsConfig , "adsenseAttributes" | "targeting" | "categoryExclusion" >
Gets general configuration options for the slot set by setConfig .

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 (устаревший)

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 ( ) : ResponseInformation
Returns the ad response information. This is based on the last ad response for the slot. If this is called when the slot has no ad, null will be returned.
Возврат
ResponseInformation The latest ad response information, or null if the slot has no ad.

getSlotElementId

getSlotElementId ( ) : string
Returns the ID of the slot div provided when the slot was defined.
Пример

JavaScript

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .addService(googletag.pubads());

slot.getSlotElementId();
// Returns 'div'.

JavaScript (устаревший)

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 []
Returns a specific custom targeting parameter set on this slot. Service-level targeting parameters are not included.
Пример

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 (устаревший)

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 []
Returns the list of all custom targeting keys set on this slot. Service-level targeting keys are not included.
Пример

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 (устаревший)

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 ) : Slot
Sets a value for an AdSense attribute on this ad slot. This will override any values set at the service level for this key.

Calling 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 (устаревший)

// 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 Имя атрибута.
value : string Attribute value.
Возврат
Slot The slot object on which the method was called.

setCategoryExclusion

setCategoryExclusion ( categoryExclusion : string ) : Slot
Sets a slot-level ad category exclusion label on this slot.
Пример

JavaScript

// Label = AirlineAd
googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setCategoryExclusion("AirlineAd")
  .addService(googletag.pubads());

JavaScript (устаревший)

// 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 ) : Slot
Sets the click URL to which users will be redirected after clicking on the ad.

The 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 (устаревший)

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 ) : Slot
Sets whether the slot div 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 (устаревший)

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.
Optional collapseBeforeAdFetch : boolean 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
Sets general configuration options for this slot.
Параметры
slotConfig : SlotSettingsConfig The configuration object.

setForceSafeFrame

setForceSafeFrame ( forceSafeFrame : boolean ) : Slot
Configures whether ads in this slot should be forced to be rendered using a SafeFrame container.

Please 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 false or 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 (устаревший)

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 ) : Slot
Sets the slot-level preferences for SafeFrame configuration. Any unrecognized keys in the config object will be ignored. The entire config will be ignored if an invalid value is passed for a recognized key.

These 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 (устаревший)

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
Sets a custom targeting parameter for this slot. Calling this method multiple times for the same key will overwrite old values. Values set here will overwrite targeting parameters set at the service-level. These keys are defined in your Google Ad Manager account.
Пример

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 (устаревший)

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
Sets custom targeting parameters for this slot, from a key:value map in a JSON object. This is the same as calling Slot.setTargeting for all the key values of the object. These keys are defined in your Google Ad Manager account.

Примечания:
  • 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 (устаревший)

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 : {
  [ adUnitPath : string ] : string | string [] ;
}
Targeting parameter key:value map.
Возврат
Slot The slot object on which the method was called.

googletag.config

Main configuration interface for page-level settings.
Интерфейсы
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"
Supported values for controlling the collapsing behavior of ad slots.
Смотрите также

InterstitialTrigger

InterstitialTrigger : "unhideWindow" | "navBar"
Supported interstitial ad triggers.

PrivacyTreatment

PrivacyTreatment : "disablePersonalization"
Supported publisher privacy treatments.

Таксономия

Taxonomy : "IAB_AUDIENCE_1_1" | "IAB_CONTENT_2_2"
Supported taxonomies for publisher provided signals (PPS) .
Смотрите также

googletag.config.AdExpansionConfig

Settings to control ad expansion.
Характеристики
enabled ?
Whether ad expansion is enabled or disabled.
Пример

JavaScript

// Enable ad slot expansion across the entire page.
googletag.setConfig({
  adExpansion: { enabled: true },
});

JavaScript (устаревший)

// 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 ?: boolean
Whether ad expansion is enabled or disabled.

Setting this value overrides the default configured in Google Ad Manager.
Смотрите также

googletag.config.AdSenseAttributesConfig

Settings to control the behavior of AdSense ads.

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"
AdSense ad format.

Optional adsense_channel_ids

adsense_channel_ids ?: string
AdSense channel IDs.

Allowed values are channel IDs separated by '+'.

Example: 271828183+314159265
Смотрите также

Optional adsense_test_mode

adsense_test_mode ?: "on"
Whether or not test mode is enabled.

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 ?: string
Language of the page on which ads are displayed.

Allowed values are valid ISO 639-1 language codes.

en : en
Смотрите также

Optional page_url

page_url ?: string
URL of the page on which ads are displayed.

Allowed values are valid URLs.

Example: http://www.example.com

googletag.config.ComponentAuctionConfig

An object representing a single component auction in a on-device ad auction.
Характеристики
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 ;
}
An auction configuration object for this component auction.

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 (устаревший)

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 : string
The configuration key associated with this component auction.

This 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

An object which defines the behavior of a single interstitial ad slot.
Характеристики
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 ?: boolean
Whether local storage consent is required to display this interstitial ad.

GPT 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 (устаревший)

// 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 > >
The interstitial trigger configuration for this interstitial ad.

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 (устаревший)

// 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

Settings to control the use of lazy loading in GPT.
Характеристики
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 ?: number
The minimum distance from the current viewport a slot must be before we request an ad, expressed as a percentage of viewport size.

Used 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 ?: number
A multiplier applied to margins on mobile devices. This multiplier is applied to both fetchMarginPercent and renderMarginPercent .

This 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 ?: number
The minimum distance from the current viewport a slot must be before we render an ad, expressed as a percentage of viewport size.

Used 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

Main configuration interface for page-level settings.

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 ?
Устарело.
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
Settings to control ad expansion.

Optional adsenseAttributes

adsenseAttributes ?: AdSenseAttributesConfig
Setting to configure AdSense attributes.

AdSense 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 (устаревший)

// 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 []
Setting to configure ad category exclusions.
Пример

JavaScript

// Label = AirlineAd.
googletag.setConfig({ categoryExclusion: ["AirlineAd"] });

// Clearing category exclusion setting.
googletag.setConfig({ categoryExclusion: null });

JavaScript (устаревший)

// 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 ?: boolean
Setting to control the horizontal centering of ads. Centering is disabled by default.

Horizontal 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 (устаревший)

// 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 ?: CollapseDivBehavior
Setting to control the collapsing behavior of ad slots.

A collapsed ad slot does not take up any space on the page.

Поддерживаемые значения:
  • 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 (устаревший)

// 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 ?: boolean
Setting to control when ads are requested.

By 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 (устаревший)

// 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 ?: LazyLoadConfig
Settings to control the use of lazy loading in GPT.

Lazy 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 (устаревший)

// 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 ?: string
Setting to geo-target line items to geographic locations.
Пример

JavaScript

// Geo-target line items to US postal code 10001.
googletag.setConfig({ location: "10001,US" });

// Clear the location setting.
googletag.setConfig({ location: null });

JavaScript (устаревший)

// 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

Settings to control publisher provided signals (PPS).

Optional privacyTreatments

privacyTreatments ?: PrivacyTreatmentsConfig
Settings to control publisher privacy treatments.

Optional safeFrame

safeFrame ?: SafeFrameConfig
Settings to control the use of SafeFrame in GPT.

Values 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 (устаревший)

// 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 ?: boolean
Setting to enable or disable Single Request Architecture (SRA).

When 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 (устаревший)

// Enable Single Request Architecture.
googletag.setConfig({ singleRequest: true });

Машинопись

// Enable Single Request Architecture.
googletag.setConfig({ singleRequest: true });
Смотрите также

Optional targeting

targeting ?: Record < string , string | string [] >
Setting to control key-value targeting.

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 (устаревший)

// 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"
Setting to control whether GPT should yield the JS thread when requesting and rendering creatives.

GPT will yield only for browsers that support the Scheduler.postTask or Scheduler.yield API.

Поддерживаемые значения:
  • 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 (устаревший)

// 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
Settings to control video ads.
Пример

JavaScript

// Enable video ads and set video content and content source IDs.
googletag.setConfig({
  videoAds: {
    enableVideoAds: true,
    videoContentId: "e1eGlRL7ju8",
    videoCmsId: "1234567",
  },
});

JavaScript (устаревший)

// 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

Settings to control publisher privacy treatments.
Характеристики
treatments
An array of publisher privacy treatments to enable.

Характеристики


лечения

treatments : "disablePersonalization" []
An array of publisher privacy treatments to enable.
Пример

JavaScript

// Disable personalization across the entire page.
googletag.setConfig({
  privacyTreatments: { treatments: ["disablePersonalization"] },
});

JavaScript (устаревший)

// 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

Publisher provided signals (PPS) configuration object.
Характеристики
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 (устаревший)

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 : Partial < Record < Taxonomy , TaxonomyData > >
An object containing Taxonomy mappings or null to clear the config.

googletag.config.SafeFrameConfig

Settings to control SafeFrame in GPT.
Характеристики
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
Whether SafeFrame should allow ad content to expand by overlaying page content.

Optional allowPushExpansion

allowPushExpansion ?: boolean
Whether SafeFrame should allow ad content to expand by pushing page content.

Optional forceSafeFrame

forceSafeFrame ?: boolean
Whether ad(s) should be forced to be rendered using a SafeFrame container.

Optional sandbox

sandbox ?: boolean
Whether SafeFrame should use the HTML5 sandbox attribute to prevent top level navigation without user interaction. The only valid value is true (cannot be forced to false ). Note that the sandbox attribute disables plugins (eg Flash).

Optional useUniqueDomain

useUniqueDomain ?: boolean
Whether SafeFrame should use randomized subdomains for Reservation creatives. Pass in null to clear the stored value.

Note: this feature is enabled by default.
Смотрите также

googletag.config.SlotSettingsConfig

Main configuration interface for slot-level settings.

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
Settings to configure ad expansion.
Смотрите также

Optional adsenseAttributes

adsenseAttributes ?: AdSenseAttributesConfig
Setting to configure AdSense attributes.

AdSense 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 (устаревший)

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 []
Setting to configure ad category exclusions.
Пример

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 (устаревший)

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 ?: string
Setting to configure the URL to which users will be redirected after clicking on the ad.

The 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 (устаревший)

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 ?: CollapseDivBehavior
Setting to configure the collapsing behavior of the ad slot.

A collapsed ad slot does not take up any space on the page.

Поддерживаемые значения:
  • 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 (устаревший)

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 []
An array of component auctions to be included in an on-device ad auction.

Optional interstitial

interstitial ?: InterstitialConfig
Settings that configure interstitial ad slot behavior.
Смотрите также

Optional safeFrame

safeFrame ?: SafeFrameConfig
Settings to configure the use of SafeFrame in GPT.

Values 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 (устаревший)

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 [] >
Setting to configure key-value targeting.

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 (устаревший)

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

An object containing the values for a single Taxonomy .
Характеристики
values
A list of Taxonomy values.

Характеристики


ценности

values : readonly string []
A list of Taxonomy values.

googletag.config.VideoAdsConfig

Settings to configure video ad related settings.
Характеристики
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 : boolean
Whether videos ads will be present on the page.

When 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 ?: string
The video content source ID.

This 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 ?: string
The video content ID.

This 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

This is the namespace that GPT uses for enum types.
Перечисления
Out Of Page Format
Out-of-page formats supported by GPT.
Traffic Source
Traffic sources supported by GPT.

Перечисления


OutOfPageFormat

OutOfPageFormat
Out-of-page formats supported by GPT.
Смотрите также
Члены перечисления
AD_ INTENTS
Ad Intents format.
BOTTOM_ ANCHOR
Anchor format where slot sticks to the bottom of the viewport.
GAME_ MANUAL_ INTERSTITIAL
Game manual interstitial format.

Note: Game manual interstitial is a limited-access format.
INTERSTITIAL
Web interstitial creative format.
LEFT_ SIDE_ RAIL
Left side rail format.
REWARDED
Rewarded format.
RIGHT_ SIDE_ RAIL
Right side rail format.
TOP_ ANCHOR
Anchor format where slot sticks to the top of the viewport.

Источник трафика

TrafficSource
Traffic sources supported by GPT.
Смотрите также
Члены перечисления
ORGANIC
Direct URL entry, site search, or app download.
PURCHASED
Traffic redirected from properties other than owned (acquired or otherwise incentivized activity).

googletag.events

This is the namespace that GPT uses for Events. Your code can react to these events using Service.addEventListener.
Интерфейсы
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

Base Interface for all GPT events. All GPT events below will have the following fields.
Характеристики
service Name
Name of the service that triggered the event.
slot
The slot that triggered the event.
Смотрите также

Характеристики


serviceName

serviceName : string
Name of the service that triggered the event.

слот

slot : Slot
The slot that triggered the event.

googletag.events.EventTypeMap

This is a pseudo-type that maps an event name to its corresponding event object type for Service.addEventListener and Service.removeEventListener . It is documented for reference and type safety purposes only.
Характеристики
game Manual Interstitial Slot Closed
game Manual Interstitial Slot Ready
impression Viewable
rewarded Slot Closed
rewarded Slot Granted
rewarded Slot Ready
rewarded Slot Video Completed
slot Onload
slot Render Ended
slot Requested
slot Response Received
slot Visibility Changed

Характеристики


gameManualInterstitialSlotClosed


gameManualInterstitialSlotReady


impressionViewable

impressionViewable : ImpressionViewableEvent
Alias for events.ImpressionViewableEvent .

rewardedSlotClosed

rewardedSlotClosed : RewardedSlotClosedEvent
Alias for events.RewardedSlotClosedEvent .

rewardedSlotGranted

rewardedSlotGranted : RewardedSlotGrantedEvent
Alias for events.RewardedSlotGrantedEvent .

rewardedSlotReady

rewardedSlotReady : RewardedSlotReadyEvent
Alias for events.RewardedSlotReadyEvent .

rewardedSlotVideoCompleted


slotOnload

slotOnload : SlotOnloadEvent
Alias for events.SlotOnloadEvent .

slotRenderEnded

slotRenderEnded : SlotRenderEndedEvent
Alias for events.SlotRenderEndedEvent .

slotRequested

slotRequested : SlotRequestedEvent
Alias for events.SlotRequestedEvent .

slotResponseReceived

slotResponseReceived : SlotResponseReceived
Alias for events.SlotResponseReceived .

slotVisibilityChanged


googletag.events.GameManualInterstitialSlotClosedEvent

Extends Event
This event is fired when a game manual interstitial slot has been closed by the user.

Note: Game manual interstitial is a limited-access format.
Характеристики
service Name
Name of the service that triggered the event.
slot
The slot that triggered the event.
Пример

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 (устаревший)

// 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

Extends Event
This event is fired when a game manual interstitial slot is ready to be shown to the user.

Note: Game manual interstitial is a limited-access format.
Характеристики
service Name
Name of the service that triggered the event.
slot
The slot that triggered the event.
Методы
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 (устаревший)

// 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 ( ) : void
Displays the game manual interstitial ad to the user.

googletag.events.ImpressionViewableEvent

Extends Event
This event is fired when an impression becomes viewable, according to the Active View criteria .
Характеристики
service Name
Name of the service that triggered the event.
slot
The slot that triggered the event.
Пример

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 (устаревший)

// 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

Extends Event
This event is fired when a rewarded ad slot is closed by the user. It may fire either before or after a reward has been granted. To determine whether a reward has been granted, use events.RewardedSlotGrantedEvent instead.
Характеристики
service Name
Name of the service that triggered the event.
slot
The slot that triggered the event.
Пример

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 (устаревший)

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

Extends Event
This event is fired when a reward is granted for viewing a rewarded ad . If the ad is closed before the criteria for granting a reward is met, this event will not fire.
Характеристики
payload
An object containing information about the reward that was granted.
service Name
Name of the service that triggered the event.
slot
The slot that triggered the event.
Пример

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 (устаревший)

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 : RewardedPayload
An object containing information about the reward that was granted.

googletag.events.RewardedSlotReadyEvent

Extends Event
This event is fired when a rewarded ad is ready to be displayed. The publisher is responsible for presenting the user an option to view the ad before displaying it.
Характеристики
service Name
Name of the service that triggered the event.
slot
The slot that triggered the event.
Методы
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 (устаревший)

// 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
Displays the rewarded ad. This method should not be called until the user has consented to view the ad.
Возврат
boolean Whether the rewarded ad was successfully displayed.

googletag.events.RewardedSlotVideoCompletedEvent

Extends Event
This event is fired when a rewarded video ad has finished playing.
Характеристики
service Name
Name of the service that triggered the event.
slot
The slot that triggered the event.
Пример

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 (устаревший)

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

Extends Event
This event is fired when the creative's iframe fires its load event. When rendering rich media ads in sync rendering mode, no iframe is used so no SlotOnloadEvent will be fired.
Характеристики
service Name
Name of the service that triggered the event.
slot
The slot that triggered the event.
Пример

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 (устаревший)

// 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

Extends Event
This event is fired when the creative code is injected into a slot. This event will occur before the creative's resources are fetched, so the creative may not be visible yet. If you need to know when all creative resources for a slot have finished loading, consider the events.SlotOnloadEvent instead.
Характеристики
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
Устарело.
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.
size
Indicates the pixel size of the rendered creative.
slot
The slot that triggered the event.
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 (устаревший)

// 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 : number
Advertiser ID of the rendered ad. Value is null for empty slots, backfill ads, and creatives rendered by services other than PubAdsService .

идентификатор кампании

campaignId : number
Campaign ID of the rendered ad. Value is null for empty slots, backfill ads, and creatives rendered by services other than PubAdsService .

companyIds

companyIds : number []
IDs of the companies that bid on the rendered backfill ad. Value is null for empty slots, reservation ads, and creatives rendered by services other than PubAdsService .

creativeId

creativeId : number
Creative ID of the rendered reservation ad. Value is null for empty slots, backfill ads, and creatives rendered by services other than PubAdsService .

creativeTemplateId

creativeTemplateId : number
Creative template ID of the rendered reservation ad. Value is null for empty slots, backfill ads, and creatives rendered by services other than PubAdsService .

isBackfill

isBackfill : boolean
Whether an ad was a backfill ad. Value is true if the ad was a backfill ad, false otherwise.

isEmpty

isEmpty : boolean
Whether an ad was returned for the slot. Value is true if no ad was returned, false otherwise.

labelIds

labelIds : number []

lineItemId

lineItemId : number
Line item ID of the rendered reservation ad. Value is null for empty slots, backfill ads, and creatives rendered by services other than PubAdsService .

responseIdentifier

responseIdentifier : string
The response identifier is a unique identifier for the ad response. This value can be used to identify and block the ad in the Ad Review Center (ARC) .

размер

size : string | number []
Indicates the pixel size of the rendered creative. Example: [728, 90] . Value is null for empty ad slots.

slotContentChanged

slotContentChanged : boolean
Whether the slot content was changed with the rendered ad. Value is true if the content was changed, false otherwise.

sourceAgnosticCreativeId

sourceAgnosticCreativeId : number
Creative ID of the rendered reservation or backfill ad. Value is null if the ad is not a reservation or line item backfill, or the creative is rendered by services other than PubAdsService .

sourceAgnosticLineItemId

sourceAgnosticLineItemId : number
Line item ID of the rendered reservation or backfill ad. Value is null if the ad is not a reservation or line item backfill, or the creative is rendered by services other than PubAdsService .

yieldGroupIds

yieldGroupIds : number []
IDs of the yield groups for the rendered backfill ad. Value is null for empty slots, reservation ads, and creatives rendered by services other than PubAdsService .

googletag.events.SlotRequestedEvent

Extends Event
This event is fired when an ad has been requested for a particular slot.
Характеристики
service Name
Name of the service that triggered the event.
slot
The slot that triggered the event.
Пример

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 (устаревший)

// 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

Extends Event
This event is fired when an ad response has been received for a particular slot.
Характеристики
service Name
Name of the service that triggered the event.
slot
The slot that triggered the event.
Пример

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 (устаревший)

// 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

Extends Event
This event is fired whenever the on-screen percentage of an ad slot's area changes. The event is throttled and will not fire more often than once every 200ms.
Характеристики
in View Percentage
The percentage of the ad's area that is visible.
service Name
Name of the service that triggered the event.
slot
The slot that triggered the event.
Пример

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 (устаревший)

// 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 : number
The percentage of the ad's area that is visible. Value is a number between 0 and 100.

googletag.secureSignals

This is the namespace that GPT uses for managing secure signals.
Интерфейсы
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

Interface for returning a secure signal for a specific bidder or provider. One of id or networkCode must be provided, but not both.

googletag.secureSignals.BidderSignalProvider

Returns a secure signal for a specific bidder.

A bidder secure signal provider consists of 2 parts:

  1. A collector function, which returns a Promise that resolves to a secure signal.
  2. An id which identifies the bidder associated with the signal.
To return a secure signal for a publisher, use secureSignals.PublisherSignalProvider instead.
Характеристики
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 (устаревший)

// 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 > )
A function which returns a Promise that resolves to a secure signal.

идентификатор

id : string
A unique identifier for the collector associated with this secure signal, as registered in Google Ad Manager.

googletag.secureSignals.PublisherSignalProvider

Returns a secure signal for a specific publisher.

A publisher signal provider consists of 2 parts:

  1. A collector function, which returns a Promise that resolves to a secure signal.
  2. A networkCode which identifies the publisher associated with the signal.
To return a secure signal for a bidder, use secureSignals.BidderSignalProvider instead.
Характеристики
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 (устаревший)

// 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 > )
A function which returns a Promise that resolves to a secure signal.

networkCode

networkCode : string
The network code (as seen in the ad unit path) for the publisher associated with this secure signal.

googletag.secureSignals.SecureSignalProvidersArray

An interface for managing secure signals.
Методы
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 ( ) : void
Clears all signals for all collectors from cache.

Calling 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
Adds a new secureSignals.SecureSignalProvider to the signal provider array and begins the signal generation process.
Параметры
provider : SecureSignalProvider The secureSignals.SecureSignalProvider object to be added to the array.