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

Googleтег

Глобальное пространство имен, которое тег издателя Google использует для своего 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
Объект Slot представляет собой отдельный рекламный блок на странице.
Псевдонимы типов
Fluid Size
Строка размера, в которой контейнер рекламы занимает 100% ширины родительского div, а затем изменяет свою высоту в соответствии с размером креативного контента.
General Size
Допустимая конфигурация размера для слота, которая может включать один или несколько размеров.
Multi Size
Список допустимых размеров.
Named Size
Указаны размеры, которые может иметь слот.
Single Size
Единственный допустимый размер для слота.
Single Size Array
Массив из двух чисел, представляющих [ширину, высоту].
Size Mapping
Сопоставление размера области просмотра с размерами рекламных объявлений.
Size Mapping Array
Список сопоставлений размеров.
Переменные
api Ready
Флаг, указывающий на то, что API GPT загружен и готов к вызову.
cmd
Ссылка на глобальную очередь команд для асинхронного выполнения вызовов, связанных с GPT.
pubads Ready
Флаг, указывающий на то, что PubAdsService включен, загружен и полностью работоспособен.
secure Signal Providers
Ссылка на массив поставщиков защищенных сигналов.
Функции
companion Ads
Возвращает ссылку на CompanionAdsService .
define Out Of Page Slot
Создает рекламный блок вне страницы, используя указанный путь к рекламному блоку.
define Slot
Создает рекламный блок с заданным путем и размером и связывает его с идентификатором элемента div на странице, который будет содержать рекламу.
destroy Slots
Уничтожает указанные слоты, удаляя все связанные с ними объекты и ссылки из GPT.
disable Publisher Console
Отключает консоль издателя Google.
display
Дает указание службам слотов отобразить слот.
enable Services
Включает все сервисы GPT, определенные для рекламных блоков на странице.
get Config
Получает общие параметры конфигурации страницы, заданные параметром setConfig .
get Version
Возвращает текущую версию GPT.
open Console
Открывает консоль издателя Google.
pubads
Возвращает ссылку на PubAdsService .
set Ad Iframe Title
Устанавливает заголовок для всех iframe-контейнеров рекламы, создаваемых PubAdsService , начиная с этого момента.
set Config
Задает общие параметры конфигурации страницы.
size Mapping
Создает новый объект SizeMappingBuilder .

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


FluidSize

FluidSize : "fluid"
Строка размера, в которой контейнер рекламы занимает 100% ширины родительского div, а затем изменяет свою высоту в соответствии с содержимым креатива. Аналогично поведению обычных блочных элементов на странице. Используется для нативной рекламы (см. соответствующую статью ).

GeneralSize

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

Многоразмерный

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

NamedSize

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

Один размер

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

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 в противном случае.

disablePublisherConsole

disablePublisherConsole ( ) : void
Отключает консоль издателя Google.
См. также

отображать

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

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

enableServices

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

getConfig

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

pubads ( ) : PubAdsService
Возвращает ссылку на PubAdsService .
Возвраты
PubAdsService Сервис Publisher Ads.

setAdIframeTitle

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

JavaScript

googletag.setAdIframeTitle("title");

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

googletag.setAdIframeTitle("title");

Машинопись

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

setConfig

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

sizeMapping

sizeMapping ( ) : SizeMappingBuilder
Создает новый объект SizeMappingBuilder .
См. также
Возвраты
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

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

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

trafficSource ?: TrafficSource
Указывает, представляют ли запросы купленный или органический трафик. Это значение заполняет параметр « Источник трафика» в отчетах Ad Manager. Если не задано, источник трафика по умолчанию в отчетах будет равен 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 Объект сервиса, на котором был вызван метод.

collapseEmptyDivs

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

disableInitialLoad

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

отображать

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

Этот метод является сокращенным эквивалентом вызова googletag.defineSlot с последующим немедленным вызовом googletag.display .

Поведение этого метода зависит от того, включена ли архитектура единого запроса (SRA) :
  • SRA включено: Все рекламные места, определенные к моменту этого вызова, будут объединены в пакет и запрошены одновременно.
  • SRA отключено (по умолчанию): запрос на размещение рекламы будет отправлен индивидуально.
Примечание: При вызове этого метода создается снимок состояния слота и страницы для обеспечения согласованности при отправке запроса на показ рекламы и отображении ответа. Любые изменения, внесенные в состояние слота или страницы после вызова этого метода (включая таргетинг, настройки конфиденциальности, принудительное использование 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 означает «когда реклама находится на расстоянии 1 области просмотра» и так далее.
  • renderMarginPercent

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

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

enableSingleRequest

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

включитьВидеорекламу

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

getAttributeKeys

getAttributeKeys ( ) : string []
Возвращает ключи атрибутов, установленные для данной службы.
Пример

JavaScript

googletag.pubads().set("adsense_background_color", "#FFFFFF");
googletag.pubads().set("adsense_border_color", "#AABBCC");
googletag.pubads().getAttributeKeys();
// Returns ['adsense_background_color', 'adsense_border_color'].

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

googletag.pubads().set("adsense_background_color", "#FFFFFF");
googletag.pubads().set("adsense_border_color", "#AABBCC");
googletag.pubads().getAttributeKeys();
// Returns ['adsense_background_color', 'adsense_border_color'].

Машинопись

googletag.pubads().set("adsense_background_color", "#FFFFFF");
googletag.pubads().set("adsense_border_color", "#AABBCC");
googletag.pubads().getAttributeKeys();
// Returns ['adsense_background_color', 'adsense_border_color'].
Возвраты
string [] Массив ключей атрибутов, заданных для этой службы. Порядок не определен.

getTargeting

getTargeting ( key : string ) : string []
Возвращает заданный пользовательский параметр таргетинга на уровне сервиса.
Пример

JavaScript

googletag.pubads().setTargeting("interests", "sports");

googletag.pubads().getTargeting("interests");
// Returns ['sports'].

googletag.pubads().getTargeting("age");
// Returns [] (empty array).

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

googletag.pubads().setTargeting("interests", "sports");

googletag.pubads().getTargeting("interests");
// Returns ['sports'].

googletag.pubads().getTargeting("age");
// Returns [] (empty array).

Машинопись

googletag.pubads().setTargeting("interests", "sports");

googletag.pubads().getTargeting("interests");
// Returns ['sports'].

googletag.pubads().getTargeting("age");
// Returns [] (empty array).
Параметры
key : string Ключ к нацеливанию, на который следует обратить внимание.
Возвраты
string [] Значения, связанные с этим ключом, или пустой массив, если такого ключа нет.

getTargetingKeys

getTargetingKeys ( ) : string []
Возвращает список всех установленных пользовательских ключей таргетинга на уровне сервиса.
Пример

JavaScript

googletag.pubads().setTargeting("interests", "sports");
googletag.pubads().setTargeting("colors", "blue");

googletag.pubads().getTargetingKeys();
// Returns ['interests', 'colors'].

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

googletag.pubads().setTargeting("interests", "sports");
googletag.pubads().setTargeting("colors", "blue");

googletag.pubads().getTargetingKeys();
// Returns ['interests', 'colors'].

Машинопись

googletag.pubads().setTargeting("interests", "sports");
googletag.pubads().setTargeting("colors", "blue");

googletag.pubads().getTargetingKeys();
// Returns ['interests', 'colors'].
Возвраты
string [] Массив целевых ключей. Порядок не определен.

isInitialLoadDisabled

isInitialLoadDisabled ( ) : boolean
Возвращает значение, указывающее, был ли успешно отключен первоначальный запрос на показ рекламы предыдущим вызовом PubAdsService.disableInitialLoad .
Возвраты
boolean Возвращает true если предыдущий вызов PubAdsService.disableInitialLoad был успешным, в противном случае false .

обновить

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

Для корректной работы во всех браузерах вызов функции refresh должен предшествовать вызову функции display для display рекламного блока. Если вызов display опущен, функция refresh может работать некорректно. При желании можно использовать метод PubAdsService.disableInitialLoad , чтобы предотвратить загрузку рекламы функцией display .

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

JavaScript

const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
googletag.display("div-1");
const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2");
googletag.display("div-2");

// This call to refresh fetches a new ad for slot1 only.
googletag.pubads().refresh([slot1]);

// This call to refresh fetches a new ad for both slot1 and slot2.
googletag.pubads().refresh([slot1, slot2]);

// This call to refresh fetches a new ad for each slot.
googletag.pubads().refresh();

// This call to refresh fetches a new ad for slot1, without changing
// the correlator.
googletag.pubads().refresh([slot1], { changeCorrelator: false });

// This call to refresh fetches a new ad for each slot, without
// changing the correlator.
googletag.pubads().refresh(null, { changeCorrelator: false });

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

var slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
googletag.display("div-1");
var slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2");
googletag.display("div-2");

// This call to refresh fetches a new ad for slot1 only.
googletag.pubads().refresh([slot1]);

// This call to refresh fetches a new ad for both slot1 and slot2.
googletag.pubads().refresh([slot1, slot2]);

// This call to refresh fetches a new ad for each slot.
googletag.pubads().refresh();

// This call to refresh fetches a new ad for slot1, without changing
// the correlator.
googletag.pubads().refresh([slot1], { changeCorrelator: false });

// This call to refresh fetches a new ad for each slot, without
// changing the correlator.
googletag.pubads().refresh(null, { changeCorrelator: false });

Машинопись

const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!;
googletag.display("div-1");
const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!;
googletag.display("div-2");

// This call to refresh fetches a new ad for slot1 only.
googletag.pubads().refresh([slot1]);

// This call to refresh fetches a new ad for both slot1 and slot2.
googletag.pubads().refresh([slot1, slot2]);

// This call to refresh fetches a new ad for each slot.
googletag.pubads().refresh();

// This call to refresh fetches a new ad for slot1, without changing
// the correlator.
googletag.pubads().refresh([slot1], { changeCorrelator: false });

// This call to refresh fetches a new ad for each slot, without
// changing the correlator.
googletag.pubads().refresh(null, { changeCorrelator: false });
См. также
Параметры
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 следует использовать с осторожностью, поскольку он может повлиять на поведение рекламных материалов, которые пытаются выйти за пределы своих iFrames или полагаются на их прямую отрисовку на странице издателя.
Пример

JavaScript

googletag.pubads().setForceSafeFrame(true);

// The following slot will be opted-out of the page-level force
// SafeFrame instruction.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")
  .setForceSafeFrame(false)
  .addService(googletag.pubads());

// The following slot will have SafeFrame forced.
googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads());

googletag.display("div-1");
googletag.display("div-2");

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

googletag.pubads().setForceSafeFrame(true);

// The following slot will be opted-out of the page-level force
// SafeFrame instruction.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")
  .setForceSafeFrame(false)
  .addService(googletag.pubads());

// The following slot will have SafeFrame forced.
googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads());

googletag.display("div-1");
googletag.display("div-2");

Машинопись

googletag.pubads().setForceSafeFrame(true);

// The following slot will be opted-out of the page-level force
// SafeFrame instruction.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")!
  .setForceSafeFrame(false)
  .addService(googletag.pubads());

// The following slot will have SafeFrame forced.
googletag.defineSlot("/1234567/news", [160, 600], "div-2")!.addService(googletag.pubads());

googletag.display("div-1");
googletag.display("div-2");
См. также
Параметры
forceSafeFrame : boolean true принудительно устанавливает отображение всей рекламы на странице в SafeFrames, а false отменяет предыдущую настройку. Установка значения false , если оно ранее не было указано, ничего не изменит.
Возвраты
PubAdsService Объект сервиса, на котором был вызван метод.

setLocation

setLocation ( address : string ) : PubAdsService
Передает информацию о местоположении с веб-сайтов, позволяя настраивать географическую привязку товаров к конкретным регионам.
Пример

JavaScript

// Postal code:
googletag.pubads().setLocation("10001,US");

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

// Postal code:
googletag.pubads().setLocation("10001,US");

Машинопись

// Postal code:
googletag.pubads().setLocation("10001,US");
Параметры
address : string Адрес в свободной форме.
Возвраты
PubAdsService Объект сервиса, на котором был вызван метод.

setPrivacySettings

setPrivacySettings ( privacySettings : PrivacySettingsConfig ) : PubAdsService
Позволяет настраивать все параметры конфиденциальности из одного 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

advertiserId : number
Идентификатор рекламодателя.

campaignId

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

креативный ID

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

creativeTemplateId

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

lineItemId

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

googletag.RewardedPayload

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

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


количество

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

тип

type : string
The type of item included in the reward (for example, "coin").

googletag.Service

Base service class that contains methods common for all services.
Методы
add Event Listener
Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page.
get Slots
Get the list of slots associated with this service.
remove Event Listener
Removes a previously registered listener.

Методы


addEventListener

addEventListener < K extends keyof EventTypeMap > ( eventType : K , listener : ( ( arg : EventTypeMap [ K ] ) => void ) ) : Service
Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page. The following events are supported: An object of the appropriate event type is passed to the listener when it is called.
Пример

JavaScript

// 1. Adding an event listener for the PubAdsService.
googletag.pubads().addEventListener("slotOnload", (event) => {
  console.log("Slot has been loaded:");
  console.log(event);
});

// 2. Adding an event listener with slot specific logic.
// Listeners operate at service level, which means that you cannot add
// a listener for an event for a specific slot only. You can, however,
// programmatically filter a listener to respond only to a certain ad
// slot, using this pattern:
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotOnload", (event) => {
  if (event.slot === targetSlot) {
    // Slot specific logic.
  }
});

JavaScript (legacy)

// 1. Adding an event listener for the PubAdsService.
googletag.pubads().addEventListener("slotOnload", function (event) {
  console.log("Slot has been loaded:");
  console.log(event);
});

// 2. Adding an event listener with slot specific logic.
// Listeners operate at service level, which means that you cannot add
// a listener for an event for a specific slot only. You can, however,
// programmatically filter a listener to respond only to a certain ad
// slot, using this pattern:
var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotOnload", function (event) {
  if (event.slot === targetSlot) {
    // Slot specific logic.
  }
});

Машинопись

// 1. Adding an event listener for the PubAdsService.
googletag.pubads().addEventListener("slotOnload", (event) => {
  console.log("Slot has been loaded:");
  console.log(event);
});

// 2. Adding an event listener with slot specific logic.
// Listeners operate at service level, which means that you cannot add
// a listener for an event for a specific slot only. You can, however,
// programmatically filter a listener to respond only to a certain ad
// slot, using this pattern:
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotOnload", (event) => {
  if (event.slot === targetSlot) {
    // Slot specific logic.
  }
});
См. также
Параметры
eventType : K A string representing the type of event generated by GPT. Event types are case sensitive.
listener : ( ( arg : EventTypeMap [ K ] ) => void ) Function that takes a single event object argument.
Возвраты
Service The service object on which the method was called.

getSlots

getSlots ( ) : Slot []
Get the list of slots associated with this service.
Возвраты
Slot [] Slots in the order in which they were added to the service.

removeEventListener

removeEventListener < K extends keyof EventTypeMap > ( eventType : K , listener : ( ( event : EventTypeMap [ K ] ) => void ) ) : void
Removes a previously registered listener.
Пример

JavaScript

googletag.cmd.push(() => {
  // Define a new ad slot.
  googletag.defineSlot("/6355419/Travel", [728, 90], "div-for-slot").addService(googletag.pubads());

  // Define a new function that removes itself via removeEventListener
  // after the impressionViewable event fires.
  const onViewableListener = (event) => {
    googletag.pubads().removeEventListener("impressionViewable", onViewableListener);
    setTimeout(() => {
      googletag.pubads().refresh([event.slot]);
    }, 30000);
  };

  // Add onViewableListener as a listener for impressionViewable events.
  googletag.pubads().addEventListener("impressionViewable", onViewableListener);
  googletag.enableServices();
});

JavaScript (legacy)

googletag.cmd.push(function () {
  // Define a new ad slot.
  googletag.defineSlot("/6355419/Travel", [728, 90], "div-for-slot").addService(googletag.pubads());

  // Define a new function that removes itself via removeEventListener
  // after the impressionViewable event fires.
  var onViewableListener = function (event) {
    googletag.pubads().removeEventListener("impressionViewable", onViewableListener);
    setTimeout(function () {
      googletag.pubads().refresh([event.slot]);
    }, 30000);
  };

  // Add onViewableListener as a listener for impressionViewable events.
  googletag.pubads().addEventListener("impressionViewable", onViewableListener);
  googletag.enableServices();
});

Машинопись

googletag.cmd.push(() => {
  // Define a new ad slot.
  googletag
    .defineSlot("/6355419/Travel", [728, 90], "div-for-slot")!
    .addService(googletag.pubads());

  // Define a new function that removes itself via removeEventListener
  // after the impressionViewable event fires.
  const onViewableListener = (event: googletag.events.ImpressionViewableEvent) => {
    googletag.pubads().removeEventListener("impressionViewable", onViewableListener);
    setTimeout(() => {
      googletag.pubads().refresh([event.slot]);
    }, 30000);
  };

  // Add onViewableListener as a listener for impressionViewable events.
  googletag.pubads().addEventListener("impressionViewable", onViewableListener);
  googletag.enableServices();
});
Параметры
eventType : K A string representing the type of event generated by GPT. Event types are case sensitive.
listener : ( ( event : EventTypeMap [ K ] ) => void ) Function that takes a single event object argument.

googletag.SizeMappingBuilder

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 (legacy)

// Mapping 1
googletag
  .sizeMapping()
  .addSize([1024, 768], [970, 250])
  .addSize([980, 690], [728, 90])
  .addSize([640, 480], "fluid")
  .addSize([0, 0], [88, 31]) // All viewports &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 (legacy)

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

Машинопись

googletag.defineSlot("/1234567/sports", [160, 600], "div")!.addService(googletag.pubads());
См. также
Параметры
service : Service The service to be added.
Возвраты
Slot The slot object on which the method was called.

clearCategoryExclusions

clearCategoryExclusions ( ) : Slot
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 (legacy)

// Set category exclusion to exclude ads with 'AirlineAd' labels.
var slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setCategoryExclusion("AirlineAd")
  .addService(googletag.pubads());

// Make an ad request. No ad with 'AirlineAd' label will be returned
// for the slot.

// Clear category exclusions so all ads can be returned.
slot.clearCategoryExclusions();

// Make an ad request. Any ad can be returned for the slot.

Машинопись

// Set category exclusion to exclude ads with 'AirlineAd' labels.
const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setCategoryExclusion("AirlineAd")
  .addService(googletag.pubads());

// Make an ad request. No ad with 'AirlineAd' label will be returned
// for the slot.

// Clear category exclusions so all ads can be returned.
slot.clearCategoryExclusions();

// Make an ad request. Any ad can be returned for the slot.
Возвраты
Slot The slot object on which the method was called.

clearTargeting

clearTargeting ( key ?: string ) : Slot
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 (legacy)

var slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setTargeting("allow_expandable", "true")
  .setTargeting("interests", ["sports", "music"])
  .setTargeting("color", "red")
  .addService(googletag.pubads());

slot.clearTargeting("color");
// Targeting 'allow_expandable' and 'interests' are still present,
// while 'color' was cleared.

slot.clearTargeting();
// All targeting has been cleared.

Машинопись

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setTargeting("allow_expandable", "true")
  .setTargeting("interests", ["sports", "music"])
  .setTargeting("color", "red")
  .addService(googletag.pubads());

slot.clearTargeting("color");
// Targeting 'allow_expandable' and 'interests' are still present,
// while 'color' was cleared.

slot.clearTargeting();
// All targeting has been cleared.
См. также
Параметры
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 (legacy)

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

var mapping = googletag
  .sizeMapping()
  .addSize([100, 100], [88, 31])
  .addSize(
    [320, 400],
    [
      [320, 50],
      [300, 50],
    ],
  )
  .build();

slot.defineSizeMapping(mapping);

Машинопись

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

const mapping = googletag
  .sizeMapping()
  .addSize([100, 100], [88, 31])
  .addSize(
    [320, 400],
    [
      [320, 50],
      [300, 50],
    ],
  )
  .build();

slot.defineSizeMapping(mapping!);
См. также
Параметры
sizeMapping : SizeMappingArray Array of size mappings. You can use SizeMappingBuilder to create it. Each size mapping is an array of two elements: SingleSizeArray and GeneralSize .
Возвраты
Slot The slot object on which the method was called.

получать

get ( key : string ) : string
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 (legacy)

var slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .set("adsense_background_color", "#FFFFFF")
  .addService(googletag.pubads());

slot.get("adsense_background_color");
// Returns '#FFFFFF'.

Машинопись

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

slot.get("adsense_background_color");
// Returns '#FFFFFF'.
См. также
Параметры
key : string Name of the attribute to look for.
Возвраты
string Current value for the attribute key, or null if the key is not present.

getAdUnitPath

getAdUnitPath ( ) : string
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 (legacy)

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

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

Машинопись

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

slot.getAdUnitPath();
// Returns '/1234567/sports'.
Возвраты
string Ad unit path.

getAttributeKeys

getAttributeKeys ( ) : string []
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 (legacy)

var slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .set("adsense_background_color", "#FFFFFF")
  .set("adsense_border_color", "#AABBCC")
  .addService(googletag.pubads());

slot.getAttributeKeys();
// Returns ['adsense_background_color', 'adsense_border_color'].

Машинопись

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .set("adsense_background_color", "#FFFFFF")
  .set("adsense_border_color", "#AABBCC")
  .addService(googletag.pubads());

slot.getAttributeKeys();
// Returns ['adsense_background_color', 'adsense_border_color'].
Возвраты
string [] Array of attribute keys. Ordering is undefined.

getCategoryExclusions

getCategoryExclusions ( ) : string []
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 (legacy)

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

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

Машинопись

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

slot.getCategoryExclusions();
// Returns ['AirlineAd', 'TrainAd'].
Возвраты
string [] The ad category exclusion labels for this slot, or an empty array if none have been set.

getConfig

getConfig ( keys : string | string [] ) : Pick < SlotSettingsConfig , "adsenseAttributes" | "targeting" | "categoryExclusion" >
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 (legacy)

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

// Get the value of the `targeting` setting.
var targetingConfig = slot.getConfig("targeting");

// Get the value of the `adsenseAttributes` and `categoryExclusion` settings.
var config = slot.getConfig(["adsenseAttributes", "categoryExclusion"]);

Машинопись

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

// Get the value of the `targeting` setting.
const targetingConfig = slot.getConfig("targeting");

// Get the value of the `adsenseAttributes` and `categoryExclusion` settings.
const config = slot.getConfig(["adsenseAttributes", "categoryExclusion"]);
Параметры
keys : string | string [] The keys of the configuration options to get.
Возвраты
Pick < SlotSettingsConfig , "adsenseAttributes" | "targeting" | "categoryExclusion" > The configuration options for the slot.

getResponseInformation

getResponseInformation ( ) : 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 (legacy)

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

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

Машинопись

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

slot.getSlotElementId();
// Returns 'div'.
Возвраты
string Slot div ID.

getTargeting

getTargeting ( key : string ) : string []
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 (legacy)

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

slot.getTargeting("allow_expandable");
// Returns ['true'].

slot.getTargeting("age");
// Returns [] (empty array).

Машинопись

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

slot.getTargeting("allow_expandable");
// Returns ['true'].

slot.getTargeting("age");
// Returns [] (empty array).
Параметры
key : string The targeting key to look for.
Возвраты
string [] The values associated with this key, or an empty array if there is no such key.

getTargetingKeys

getTargetingKeys ( ) : string []
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 (legacy)

var slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setTargeting("allow_expandable", "true")
  .setTargeting("interests", ["sports", "music"])
  .addService(googletag.pubads());

slot.getTargetingKeys();
// Returns ['interests', 'allow_expandable'].

Машинопись

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setTargeting("allow_expandable", "true")
  .setTargeting("interests", ["sports", "music"])
  .addService(googletag.pubads());

slot.getTargetingKeys();
// Returns ['interests', 'allow_expandable'].
Возвраты
string [] Array of targeting keys. Ordering is undefined.

набор

set ( key : string , value : string ) : 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 (legacy)

// Setting an attribute on a single ad slot.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .set("adsense_background_color", "#FFFFFF")
  .addService(googletag.pubads());

Машинопись

// Setting an attribute on a single ad slot.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .set("adsense_background_color", "#FFFFFF")
  .addService(googletag.pubads());
См. также
Параметры
key : string The name of the attribute.
value : string Attribute value.
Возвраты
Slot The slot object on which the method was called.

setCategoryExclusion

setCategoryExclusion ( categoryExclusion : string ) : Slot
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 (legacy)

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

Машинопись

// Label = AirlineAd
googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setCategoryExclusion("AirlineAd")
  .addService(googletag.pubads());
См. также
Параметры
categoryExclusion : string The ad category exclusion label to add.
Возвраты
Slot The slot object on which the method was called.

setClickUrl

setClickUrl ( value : string ) : 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 (legacy)

googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setClickUrl("http://www.example.com?original_click_url=")
  .addService(googletag.pubads());

Машинопись

googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setClickUrl("http://www.example.com?original_click_url=")
  .addService(googletag.pubads());
Параметры
value : string The click URL to set.
Возвраты
Slot The slot object on which the method was called.

setCollapseEmptyDiv

setCollapseEmptyDiv ( collapse : boolean , collapseBeforeAdFetch ?: boolean ) : 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 (legacy)

googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")
  .setCollapseEmptyDiv(true, true)
  .addService(googletag.pubads());
// The above will cause the div for this slot to be collapsed
// when the page is loaded, before ads are requested.

googletag
  .defineSlot("/1234567/sports", [160, 600], "div-2")
  .setCollapseEmptyDiv(true)
  .addService(googletag.pubads());
// The above will cause the div for this slot to be collapsed
// only after GPT detects that no ads are available for the slot.

Машинопись

googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")!
  .setCollapseEmptyDiv(true, true)
  .addService(googletag.pubads());
// The above will cause the div for this slot to be collapsed
// when the page is loaded, before ads are requested.

googletag
  .defineSlot("/1234567/sports", [160, 600], "div-2")!
  .setCollapseEmptyDiv(true)
  .addService(googletag.pubads());
// The above will cause the div for this slot to be collapsed
// only after GPT detects that no ads are available for the slot.
См. также
Параметры
collapse : boolean Whether to collapse the slot if no ad is returned.
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 (legacy)

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

Машинопись

googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setForceSafeFrame(true)
  .addService(googletag.pubads());
См. также
Параметры
forceSafeFrame : boolean true to force all ads in this slot to be rendered in SafeFrames and false to opt-out of a page-level setting (if present). Setting this to false when not specified at the page-level won't change anything.
Возвраты
Slot The slot object on which the method was called.

setSafeFrameConfig

setSafeFrameConfig ( config : SafeFrameConfig ) : 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 (legacy)

googletag.pubads().setForceSafeFrame(true);

// The following slot will have a sandboxed safeframe that only
// disallows top-level navigation.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")
  .setSafeFrameConfig({ sandbox: true })
  .addService(googletag.pubads());

// The following slot will inherit page-level settings.
googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads());

googletag.display("div-1");
googletag.display("div-2");

Машинопись

googletag.pubads().setForceSafeFrame(true);

// The following slot will have a sandboxed safeframe that only
// disallows top-level navigation.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")!
  .setSafeFrameConfig({ sandbox: true })
  .addService(googletag.pubads());

// The following slot will inherit page-level settings.
googletag.defineSlot("/1234567/news", [160, 600], "div-2")!.addService(googletag.pubads());

googletag.display("div-1");
googletag.display("div-2");
См. также
Параметры
config : SafeFrameConfig The configuration object.
Возвраты
Slot The slot object on which the method was called.

setTargeting

setTargeting ( key : string , value : string | string [] ) : Slot
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 (legacy)

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

// Example with a single value for a key.
slot.setTargeting("allow_expandable", "true");

// Example with multiple values for a key inside in an array.
slot.setTargeting("interests", ["sports", "music"]);

Машинопись

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

// Example with a single value for a key.
slot.setTargeting("allow_expandable", "true");

// Example with multiple values for a key inside in an array.
slot.setTargeting("interests", ["sports", "music"]);
См. также
Параметры
key : string Targeting parameter key.
value : string | string [] Targeting parameter value or array of values.
Возвраты
Slot The slot object on which the method was called.

updateTargetingFromMap

updateTargetingFromMap ( map : {
  [ adUnitPath : string ] : string | string [] ;
} ) : Slot
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 (legacy)

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

slot.updateTargetingFromMap({
  color: "red",
  interests: ["sports", "music", "movies"],
});

Машинопись

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

slot.updateTargetingFromMap({
  color: "red",
  interests: ["sports", "music", "movies"],
});
Параметры
map : {
  [ 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 (legacy)

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

Машинопись

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

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


Optional enabled

enabled ?: 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.

Example: 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 (legacy)

var componentAuctionConfig = {
  // Seller URL should be https and the same as decisionLogicURL's origin
  seller: "https://testSeller.com",
  decisionLogicURL: "https://testSeller.com/ssp/decision-logic.js",
  interestGroupBuyers: ["https://example-buyer.com"],
  auctionSignals: { auction_signals: "auction_signals" },
  sellerSignals: { seller_signals: "seller_signals" },
  perBuyerSignals: {
    // listed on interestGroupBuyers
    "https://example-buyer.com": {
      per_buyer_signals: "per_buyer_signals",
    },
  },
};

var auctionSlot = googletag.defineSlot("/1234567/example", [160, 600]);

// To add configKey to the component auction:
auctionSlot.setConfig({
  componentAuction: [
    {
      configKey: "https://testSeller.com",
      auctionConfig: componentAuctionConfig,
    },
  ],
});

// To remove configKey from the component auction:
auctionSlot.setConfig({
  componentAuction: [
    {
      configKey: "https://testSeller.com",
      auctionConfig: null,
    },
  ],
});

Машинопись

const componentAuctionConfig = {
  // Seller URL should be https and the same as decisionLogicURL's origin
  seller: "https://testSeller.com",
  decisionLogicURL: "https://testSeller.com/ssp/decision-logic.js",
  interestGroupBuyers: ["https://example-buyer.com"],
  auctionSignals: { auction_signals: "auction_signals" },
  sellerSignals: { seller_signals: "seller_signals" },
  perBuyerSignals: {
    // listed on interestGroupBuyers
    "https://example-buyer.com": {
      per_buyer_signals: "per_buyer_signals",
    },
  },
};

const auctionSlot = googletag.defineSlot("/1234567/example", [160, 600])!;

// To add configKey to the component auction:
auctionSlot.setConfig({
  componentAuction: [
    {
      configKey: "https://testSeller.com",
      auctionConfig: componentAuctionConfig,
    },
  ],
});

// To remove configKey from the component auction:
auctionSlot.setConfig({
  componentAuction: [
    {
      configKey: "https://testSeller.com",
      auctionConfig: null,
    },
  ],
});
См. также

configKey

configKey : 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 (legacy)

// Opt out of showing interstitials to users
// without local storage consent.
var interstitialSlot = googletag.defineOutOfPageSlot(
  "/1234567/sports",
  googletag.enums.OutOfPageFormat.INTERSTITIAL,
);

interstitialSlot.setConfig({
  interstitial: {
    requireStorageAccess: true, // defaults to false
  },
});

Машинопись

// Opt out of showing interstitials to users
// without local storage consent.
const interstitialSlot = googletag.defineOutOfPageSlot(
  "/1234567/sports",
  googletag.enums.OutOfPageFormat.INTERSTITIAL,
)!;

interstitialSlot.setConfig({
  interstitial: {
    requireStorageAccess: true, // defaults to false
  },
});
См. также

Optional triggers

triggers ?: Partial < Record < InterstitialTrigger , boolean > >
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 (legacy)

// Define a GPT managed web interstitial ad slot.
var interstitialSlot = googletag.defineOutOfPageSlot(
  "/1234567/sports",
  googletag.enums.OutOfPageFormat.INTERSTITIAL,
);

// Enable optional interstitial triggers.
// Change this value to false to disable.
var enableTriggers = true;

interstitialSlot.setConfig({
  interstitial: {
    triggers: {
      navBar: enableTriggers,
      unhideWindow: enableTriggers,
    },
  },
});

Машинопись

// Define a GPT managed web interstitial ad slot.
const interstitialSlot = googletag.defineOutOfPageSlot(
  "/1234567/sports",
  googletag.enums.OutOfPageFormat.INTERSTITIAL,
)!;

// Enable optional interstitial triggers.
// Change this value to false to disable.
const enableTriggers = true;

interstitialSlot.setConfig({
  interstitial: {
    triggers: {
      navBar: enableTriggers,
      unhideWindow: enableTriggers,
    },
  },
});
См. также

googletag.config.LazyLoadConfig

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 ?
Deprecated.
category Exclusion ?
Setting to configure ad category exclusions.
centering ?
Setting to control the horizontal centering of ads.
collapse Div ?
Setting to control the collapsing behavior of ad slots.
disable Initial Load ?
Setting to control when ads are requested.
lazy Load ?
Settings to control the use of lazy loading in GPT.
location ?
Setting to geo-target line items to geographic locations.
pps ?
Settings to control publisher provided signals (PPS).
privacy Treatments ?
Settings to control publisher privacy treatments.
safe Frame ?
Settings to control the use of SafeFrame in GPT.
single Request ?
Setting to enable or disable Single Request Architecture (SRA).
targeting ?
Setting to control key-value targeting.
thread Yield ?
Setting to control whether GPT should yield the JS thread when requesting and rendering creatives.
video Ads ?
Settings to control video ads.

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


Optional adExpansion

adExpansion ?: AdExpansionConfig
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 (legacy)

// Set the document language and page URL.
googletag.setConfig({
  adsenseAttributes: { document_language: "en", page_url: "http://www.example.com" },
});

// Clear the page URL only.
googletag.setConfig({ adsenseAttributes: { page_url: null } });

// Clear all AdSense attributes.
googletag.setConfig({ adsenseAttributes: null });

Машинопись

// Set the document language and page URL.
googletag.setConfig({
  adsenseAttributes: { document_language: "en", page_url: "http://www.example.com" },
});

// Clear the page URL only.
googletag.setConfig({ adsenseAttributes: { page_url: null } });

// Clear all AdSense attributes.
googletag.setConfig({ adsenseAttributes: null });

Optional adYield

adYield ?: "DISABLED" | "ENABLED_ALL_SLOTS"

Optional categoryExclusion

categoryExclusion ?: string []
Setting to configure ad category exclusions.
Пример

JavaScript

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

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

JavaScript (legacy)

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

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

Машинопись

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

// Clearing category exclusion setting.
googletag.setConfig({ categoryExclusion: null });
См. также

Optional centering

centering ?: 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 (legacy)

// Make ads centered.
googletag.setConfig({ centering: true });

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

Машинопись

// Make ads centered.
googletag.setConfig({ centering: true });

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

Optional collapseDiv

collapseDiv ?: CollapseDivBehavior
Setting to control the collapsing behavior of ad slots.

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

Supported values:
  • null (default): The slot will not be collapsed.
  • DISABLED : The slot will not collapse, whether or not an ad is returned.
  • BEFORE_FETCH : The slot will start out collapsed, and expand when an ad is returned.
  • ON_NO_FILL : The slot will start out expanded, and collapse if no ad is returned.
Пример

JavaScript

// Collapse the div for this slot if no ad is returned.
googletag.setConfig({ collapseDiv: "ON_NO_FILL" });

// Collapse the div for this slot by default, and expand only
// if an ad is returned.
googletag.setConfig({ collapseDiv: "BEFORE_FETCH" });

// Do not collapse the div for this slot.
googletag.setConfig({ collapseDiv: "DISABLED" });

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

JavaScript (legacy)

// Collapse the div for this slot if no ad is returned.
googletag.setConfig({ collapseDiv: "ON_NO_FILL" });

// Collapse the div for this slot by default, and expand only
// if an ad is returned.
googletag.setConfig({ collapseDiv: "BEFORE_FETCH" });

// Do not collapse the div for this slot.
googletag.setConfig({ collapseDiv: "DISABLED" });

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

Машинопись

// Collapse the div for this slot if no ad is returned.
googletag.setConfig({ collapseDiv: "ON_NO_FILL" });

// Collapse the div for this slot by default, and expand only
// if an ad is returned.
googletag.setConfig({ collapseDiv: "BEFORE_FETCH" });

// Do not collapse the div for this slot.
googletag.setConfig({ collapseDiv: "DISABLED" });

// Clear the collapse setting.
googletag.setConfig({ collapseDiv: null });
См. также

Optional disableInitialLoad

disableInitialLoad ?: 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 (legacy)

// Prevent requesting ads when `display()` is called.
googletag.setConfig({ disableInitialLoad: true });

Машинопись

// Prevent requesting ads when `display()` is called.
googletag.setConfig({ disableInitialLoad: true });
См. также

Optional lazyLoad

lazyLoad ?: 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 (legacy)

// Enable lazy loading.
googletag.setConfig({
  lazyLoad: {
    // Fetch slots within 5 viewports.
    fetchMarginPercent: 500,
    // Render slots within 2 viewports.
    renderMarginPercent: 200,
    // Double the above values on mobile.
    mobileScaling: 2.0,
  },
});

// Clear fetch margin only.
googletag.setConfig({
  lazyLoad: { fetchMarginPercent: null },
});

// Clear all lazy loading settings.
googletag.setConfig({ lazyLoad: null });

Машинопись

// Enable lazy loading.
googletag.setConfig({
  lazyLoad: {
    // Fetch slots within 5 viewports.
    fetchMarginPercent: 500,
    // Render slots within 2 viewports.
    renderMarginPercent: 200,
    // Double the above values on mobile.
    mobileScaling: 2.0,
  },
});

// Clear fetch margin only.
googletag.setConfig({
  lazyLoad: { fetchMarginPercent: null },
});

// Clear all lazy loading settings.
googletag.setConfig({ lazyLoad: null });
См. также

Optional location

location ?: string
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 (legacy)

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

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

Машинопись

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

// Clear the location setting.
googletag.setConfig({ location: null });
См. также

Optional pps

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 (legacy)

// Force SafeFrame for all ads on the page.
googletag.setConfig({
  safeFrame: { forceSafeFrame: true },
});

// Configure SafeFrame to allow overlay expansion.
googletag.setConfig({
  safeFrame: { allowOverlayExpansion: true },
});

// Clear forceSafeFrame setting.
googletag.setConfig({
  safeFrame: { forceSafeFrame: null },
});

// Clear all SafeFrame settings.
googletag.setConfig({ safeFrame: null });

Машинопись

// Force SafeFrame for all ads on the page.
googletag.setConfig({
  safeFrame: { forceSafeFrame: true },
});

// Configure SafeFrame to allow overlay expansion.
googletag.setConfig({
  safeFrame: { allowOverlayExpansion: true },
});

// Clear forceSafeFrame setting.
googletag.setConfig({
  safeFrame: { forceSafeFrame: null },
});

// Clear all SafeFrame settings.
googletag.setConfig({ safeFrame: null });

Optional singleRequest

singleRequest ?: 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 (legacy)

// 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 (legacy)

// Setting a single targeting key-value.
googletag.setConfig({ targeting: { interests: "sports" } });

// Setting multiple values for a single targeting key
googletag.setConfig({ targeting: { interests: ["sports", "music"] } });

// Setting multiple targeting key-values at once.
googletag.setConfig({ targeting: { interests: ["sports", "music"], color: "red" } });

// Clearing a single targeting key.
googletag.setConfig({ targeting: { interests: null } });

Машинопись

// Setting a single targeting key-value.
googletag.setConfig({ targeting: { interests: "sports" } });

// Setting multiple values for a single targeting key
googletag.setConfig({ targeting: { interests: ["sports", "music"] } });

// Setting multiple targeting key-values at once.
googletag.setConfig({ targeting: { interests: ["sports", "music"], color: "red" } });

// Clearing a single targeting key.
googletag.setConfig({ targeting: { interests: null } });
См. также

Optional threadYield

threadYield ?: "DISABLED" | "ENABLED_ALL_SLOTS"
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.

Supported values:
  • null (default): GPT will yield the JS thread for slots outside of the viewport.
  • ENABLED_ALL_SLOTS : GPT will yield the JS thread for all slots regardless of whether the slot is within the viewport.
  • DISABLED : GPT will not yield the JS thread.
Пример

JavaScript

// Disable yielding.
googletag.setConfig({ threadYield: "DISABLED" });

// Enable yielding for all slots.
googletag.setConfig({ threadYield: "ENABLED_ALL_SLOTS" });

// Enable yielding only for slots outside of the viewport (default).
googletag.setConfig({ threadYield: null });

JavaScript (legacy)

// Disable yielding.
googletag.setConfig({ threadYield: "DISABLED" });

// Enable yielding for all slots.
googletag.setConfig({ threadYield: "ENABLED_ALL_SLOTS" });

// Enable yielding only for slots outside of the viewport (default).
googletag.setConfig({ threadYield: null });

Машинопись

// Disable yielding.
googletag.setConfig({ threadYield: "DISABLED" });

// Enable yielding for all slots.
googletag.setConfig({ threadYield: "ENABLED_ALL_SLOTS" });

// Enable yielding only for slots outside of the viewport (default).
googletag.setConfig({ threadYield: null });
См. также

Optional videoAds

videoAds ?: VideoAdsConfig
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 (legacy)

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

Машинопись

// Enable video ads and set video content and content source IDs.
googletag.setConfig({
  videoAds: {
    enableVideoAds: true,
    videoContentId: "e1eGlRL7ju8",
    videoCmsId: "1234567",
  },
});
См. также

googletag.config.PrivacyTreatmentsConfig

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 (legacy)

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

Машинопись

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

googletag.config.PublisherProvidedSignalsConfig

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 (legacy)

googletag.setConfig({
  pps: {
    taxonomies: {
      IAB_AUDIENCE_1_1: { values: ["6", "626"] },
      // '6' = 'Demographic | Age Range | 30-34'
      // '626' = 'Interest | Sports | Darts'
      IAB_CONTENT_2_2: { values: ["48", "127"] },
      // '48' = 'Books and Literature | Fiction'
      // '127' = 'Careers | Job Search'
    },
  },
});

Машинопись

googletag.setConfig({
  pps: {
    taxonomies: {
      IAB_AUDIENCE_1_1: { values: ["6", "626"] },
      // '6' = 'Demographic | Age Range | 30-34'
      // '626' = 'Interest | Sports | Darts'
      IAB_CONTENT_2_2: { values: ["48", "127"] },
      // '48' = 'Books and Literature | Fiction'
      // '127' = 'Careers | Job Search'
    },
  },
});
См. также

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


taxonomies

taxonomies : Partial < Record < Taxonomy , TaxonomyData > >
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 (legacy)

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

// Set the AdSense ad format and channel IDs.
slot.setConfig({
  adsenseAttributes: {
    adsense_ad_format: "120x240_as",
    adsense_channel_ids: "271828183+314159265",
  },
});

// Clear the AdSense channel IDs only.
slot.setConfig({ adsenseAttributes: { adsense_channel_ids: null } });

// Clear all AdSense attributes.
slot.setConfig({ adsenseAttributes: null });

Машинопись

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

// Set the AdSense ad format and channel IDs.
slot.setConfig({
  adsenseAttributes: {
    adsense_ad_format: "120x240_as",
    adsense_channel_ids: "271828183+314159265",
  },
});

// Clear the AdSense channel IDs only.
slot.setConfig({ adsenseAttributes: { adsense_channel_ids: null } });

// Clear all AdSense attributes.
slot.setConfig({ adsenseAttributes: null });

Optional categoryExclusion

categoryExclusion ?: string []
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 (legacy)

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

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

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

Машинопись

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

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

// Clearing category exclusion setting.
slot.setConfig({ categoryExclusion: null });
См. также

Optional clickUrl

clickUrl ?: 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 (legacy)

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

// Sets the click URL to 'http://www.example.com?original_click_url='.
slot.setConfig({
  clickUrl: "http://www.example.com?original_click_url=",
});

// Clears the click URL.
slot.setConfig({
  clickUrl: null,
});

Машинопись

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

// Sets the click URL to 'http://www.example.com?original_click_url='.
slot.setConfig({
  clickUrl: "http://www.example.com?original_click_url=",
});

// Clears the click URL.
slot.setConfig({
  clickUrl: null,
});

Optional collapseDiv

collapseDiv ?: CollapseDivBehavior
Setting to configure the collapsing behavior of the ad slot.

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

Supported values:
  • null (default): The slot will not be collapsed.
  • DISABLED : The slot will not collapse, whether or not an ad is returned.
  • BEFORE_FETCH : The slot will start out collapsed, and expand when an ad is returned.
  • ON_NO_FILL : The slot will start out expanded, and collapse if no ad is returned.
Пример

JavaScript

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

// Collapse the div for this slot if no ad is returned.
slot.setConfig({
  collapseDiv: "ON_NO_FILL",
});

// Collapse the div for this slot by default, and expand only
// if an ad is returned.
slot.setConfig({
  collapseDiv: "BEFORE_FETCH",
});

// Do not collapse the div for this slot.
slot.setConfig({
  collapseDiv: "DISABLED",
});

// Clear the collapse setting.
slot.setConfig({
  collapseDiv: null,
});

JavaScript (legacy)

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

// Collapse the div for this slot if no ad is returned.
slot.setConfig({
  collapseDiv: "ON_NO_FILL",
});

// Collapse the div for this slot by default, and expand only
// if an ad is returned.
slot.setConfig({
  collapseDiv: "BEFORE_FETCH",
});

// Do not collapse the div for this slot.
slot.setConfig({
  collapseDiv: "DISABLED",
});

// Clear the collapse setting.
slot.setConfig({
  collapseDiv: null,
});

Машинопись

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

// Collapse the div for this slot if no ad is returned.
slot.setConfig({
  collapseDiv: "ON_NO_FILL",
});

// Collapse the div for this slot by default, and expand only
// if an ad is returned.
slot.setConfig({
  collapseDiv: "BEFORE_FETCH",
});

// Do not collapse the div for this slot.
slot.setConfig({
  collapseDiv: "DISABLED",
});

// Clear the collapse setting.
slot.setConfig({
  collapseDiv: null,
});
См. также

Optional componentAuction

componentAuction ?: ComponentAuctionConfig []
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 (legacy)

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

// Force SafeFrame for the slot.
slot.setConfig({
  safeFrame: { forceSafeFrame: true },
});

// Configure SafeFrame to allow overlay expansion for the slot.
slot.setConfig({
  safeFrame: { allowOverlayExpansion: true },
});

// Clear forceSafeFrame setting for the slot.
slot.setConfig({
  safeFrame: { forceSafeFrame: null },
});

// Clear all SafeFrame settings for the slot.
slot.setConfig({ safeFrame: null });

Машинопись

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

// Force SafeFrame for the slot.
slot.setConfig({
  safeFrame: { forceSafeFrame: true },
});

// Configure SafeFrame to allow overlay expansion for the slot.
slot.setConfig({
  safeFrame: { allowOverlayExpansion: true },
});

// Clear forceSafeFrame setting for the slot.
slot.setConfig({
  safeFrame: { forceSafeFrame: null },
});

// Clear all SafeFrame settings for the slot.
slot.setConfig({ safeFrame: null });

Optional targeting

targeting ?: Record < string , string | string [] >
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 (legacy)

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

// Setting a single targeting key-value.
slot.setConfig({ targeting: { interests: "sports" } });

// Setting multiple values for a single targeting key.
slot.setConfig({ targeting: { interests: ["sports", "music"] } });

// Setting multiple targeting key-values at once.
slot.setConfig({ targeting: { interests: ["sports", "music"], color: "red" } });

// Clearing a single targeting key.
slot.setConfig({ targeting: { interests: null } });

// Clear all targeting keys.
slot.setConfig({ targeting: null });

Машинопись

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

// Setting a single targeting key-value.
slot.setConfig({ targeting: { interests: "sports" } });

// Setting multiple values for a single targeting key.
slot.setConfig({ targeting: { interests: ["sports", "music"] } });

// Setting multiple targeting key-values at once.
slot.setConfig({ targeting: { interests: ["sports", "music"], color: "red" } });

// Clearing a single targeting key.
slot.setConfig({ targeting: { interests: null } });

// Clear all targeting keys.
slot.setConfig({ targeting: null });
См. также

googletag.config.TaxonomyData

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.
См. также
Enumeration Members
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

TrafficSource
Traffic sources supported by GPT.
См. также
Enumeration Members
ORGANIC
Direct URL entry, site search, or app download.
PURCHASED
Traffic redirected from properties other than owned (acquired or otherwise incentivized activity).

googletag.events

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 (legacy)

// This listener is called when a game manual interstitial slot is closed.
var targetSlot = googletag.defineOutOfPageSlot(
  "/1234567/example",
  googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL,
);

// Slot returns null if the page or device does not support game manual interstitial ads.
if (targetSlot) {
  targetSlot.addService(googletag.pubads());

  googletag.pubads().addEventListener("gameManualInterstitialSlotClosed", function (event) {
    var slot = event.slot;
    console.log("Game manual interstital slot", slot.getSlotElementId(), "is closed.");

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}

Машинопись

// This listener is called when a game manual interstitial slot is closed.
const targetSlot = googletag.defineOutOfPageSlot(
  "/1234567/example",
  googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL,
);

// Slot returns null if the page or device does not support game manual interstitial ads.
if (targetSlot) {
  targetSlot.addService(googletag.pubads());

  googletag.pubads().addEventListener("gameManualInterstitialSlotClosed", (event) => {
    const slot = event.slot;
    console.log("Game manual interstital slot", slot.getSlotElementId(), "is closed.");

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
См. также

googletag.events.GameManualInterstitialSlotReadyEvent

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 (legacy)

// This listener is called when a game manual interstitial slot is ready to
// be displayed.
var targetSlot = googletag.defineOutOfPageSlot(
  "/1234567/example",
  googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL,
);

// Slot returns null if the page or device does not support game manual interstitial ads.
if (targetSlot) {
  targetSlot.addService(googletag.pubads());

  googletag.pubads().addEventListener("gameManualInterstitialSlotReady", function (event) {
    var slot = event.slot;
    console.log(
      "Game manual interstital slot",
      slot.getSlotElementId(),
      "is ready to be displayed.",
    );

    // Replace with custom logic.
    var displayGmiAd = true;
    if (displayGmiAd) {
      event.makeGameManualInterstitialVisible();
    }

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}

Машинопись

// This listener is called when a game manual interstitial slot is ready to
// be displayed.
const targetSlot = googletag.defineOutOfPageSlot(
  "/1234567/example",
  googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL,
);

// Slot returns null if the page or device does not support game manual interstitial ads.
if (targetSlot) {
  targetSlot.addService(googletag.pubads());

  googletag.pubads().addEventListener("gameManualInterstitialSlotReady", (event) => {
    const slot = event.slot;
    console.log(
      "Game manual interstital slot",
      slot.getSlotElementId(),
      "is ready to be displayed.",
    );

    // Replace with custom logic.
    const displayGmiAd = true;
    if (displayGmiAd) {
      event.makeGameManualInterstitialVisible();
    }

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
См. также

Методы


makeGameManualInterstitialVisible

makeGameManualInterstitialVisible ( ) : boolean
Displays the game manual interstitial ad to the user. Returns whether the ad was successfully displayed.
Возвраты
boolean

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 (legacy)

// This listener is called when an impression becomes viewable.
var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("impressionViewable", function (event) {
  var slot = event.slot;
  console.log("Impression for slot", slot.getSlotElementId(), "became viewable.");

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});

Машинопись

// This listener is called when an impression becomes viewable.
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("impressionViewable", (event) => {
  const slot = event.slot;
  console.log("Impression for slot", slot.getSlotElementId(), "became viewable.");

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
См. также

googletag.events.RewardedSlotClosedEvent

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 (legacy)

var targetSlot = googletag.defineOutOfPageSlot(
  "/1234567/example",
  googletag.enums.OutOfPageFormat.REWARDED,
);

// Slot returns null if the page or device does not support rewarded ads.
if (targetSlot) {
  targetSlot.addService(googletag.pubads());

  // This listener is called when the user closes a rewarded ad slot.
  googletag.pubads().addEventListener("rewardedSlotClosed", function (event) {
    var slot = event.slot;
    console.log("Rewarded ad slot", slot.getSlotElementId(), "has been closed.");

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}

Машинопись

const targetSlot = googletag.defineOutOfPageSlot(
  "/1234567/example",
  googletag.enums.OutOfPageFormat.REWARDED,
);

// Slot returns null if the page or device does not support rewarded ads.
if (targetSlot) {
  targetSlot.addService(googletag.pubads());

  // This listener is called when the user closes a rewarded ad slot.
  googletag.pubads().addEventListener("rewardedSlotClosed", (event) => {
    const slot = event.slot;
    console.log("Rewarded ad slot", slot.getSlotElementId(), "has been closed.");

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
См. также

googletag.events.RewardedSlotGrantedEvent

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 (legacy)

var targetSlot = googletag.defineOutOfPageSlot(
  "/1234567/example",
  googletag.enums.OutOfPageFormat.REWARDED,
);

// Slot returns null if the page or device does not support rewarded ads.
if (targetSlot) {
  targetSlot.addService(googletag.pubads());

  // This listener is called whenever a reward is granted for a
  // rewarded ad.
  googletag.pubads().addEventListener("rewardedSlotGranted", function (event) {
    var _a, _b;
    var slot = event.slot;
    console.group("Reward granted for slot", slot.getSlotElementId(), ".");

    // Log details of the reward.
    console.log("Reward type:", (_a = event.payload) === null || _a === void 0 ? void 0 : _a.type);
    console.log(
      "Reward amount:",
      (_b = event.payload) === null || _b === void 0 ? void 0 : _b.amount,
    );
    console.groupEnd();

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}

Машинопись

const targetSlot = googletag.defineOutOfPageSlot(
  "/1234567/example",
  googletag.enums.OutOfPageFormat.REWARDED,
);

// Slot returns null if the page or device does not support rewarded ads.
if (targetSlot) {
  targetSlot.addService(googletag.pubads());

  // This listener is called whenever a reward is granted for a
  // rewarded ad.
  googletag.pubads().addEventListener("rewardedSlotGranted", (event) => {
    const slot = event.slot;
    console.group("Reward granted for slot", slot.getSlotElementId(), ".");

    // Log details of the reward.
    console.log("Reward type:", event.payload?.type);
    console.log("Reward amount:", event.payload?.amount);
    console.groupEnd();

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
См. также

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


полезная нагрузка

payload : 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 (legacy)

// This listener is called when a rewarded ad slot becomes ready to be
// displayed.
var targetSlot = googletag.defineOutOfPageSlot(
  "/1234567/example",
  googletag.enums.OutOfPageFormat.REWARDED,
);

// Slot returns null if the page or device does not support rewarded ads.
if (targetSlot) {
  targetSlot.addService(googletag.pubads());

  // This listener is called whenever a reward is granted for a
  // rewarded ad.
  googletag.pubads().addEventListener("rewardedSlotReady", function (event) {
    var slot = event.slot;
    console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed.");

    // Replace with custom logic.
    var userHasConsented = true;
    if (userHasConsented) {
      event.makeRewardedVisible();
    }

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}

Машинопись

// This listener is called when a rewarded ad slot becomes ready to be
// displayed.
const targetSlot = googletag.defineOutOfPageSlot(
  "/1234567/example",
  googletag.enums.OutOfPageFormat.REWARDED,
);

// Slot returns null if the page or device does not support rewarded ads.
if (targetSlot) {
  targetSlot.addService(googletag.pubads());

  // This listener is called whenever a reward is granted for a
  // rewarded ad.
  googletag.pubads().addEventListener("rewardedSlotReady", (event) => {
    const slot = event.slot;
    console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed.");

    // Replace with custom logic.
    const userHasConsented = true;
    if (userHasConsented) {
      event.makeRewardedVisible();
    }

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
См. также

Методы


makeRewardedVisible

makeRewardedVisible ( ) : boolean
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 (legacy)

var targetSlot = googletag.defineOutOfPageSlot(
  "/1234567/example",
  googletag.enums.OutOfPageFormat.REWARDED,
);

// Slot returns null if the page or device does not support rewarded ads.
if (targetSlot) {
  targetSlot.addService(googletag.pubads());

  // This listener is called when the video in a rewarded ad slot has
  // finished playing.
  googletag.pubads().addEventListener("rewardedSlotVideoCompleted", function (event) {
    var slot = event.slot;
    console.log("Video in rewarded ad slot", slot.getSlotElementId(), "has finished playing.");

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}

Машинопись

const targetSlot = googletag.defineOutOfPageSlot(
  "/1234567/example",
  googletag.enums.OutOfPageFormat.REWARDED,
);

// Slot returns null if the page or device does not support rewarded ads.
if (targetSlot) {
  targetSlot.addService(googletag.pubads());

  // This listener is called when the video in a rewarded ad slot has
  // finished playing.
  googletag.pubads().addEventListener("rewardedSlotVideoCompleted", (event) => {
    const slot = event.slot;
    console.log("Video in rewarded ad slot", slot.getSlotElementId(), "has finished playing.");

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
См. также

googletag.events.SlotOnloadEvent

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 (legacy)

// This listener is called when a creative iframe load event fires.
var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotOnload", function (event) {
  var slot = event.slot;
  console.log("Creative iframe for slot", slot.getSlotElementId(), "has loaded.");

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});

Машинопись

// This listener is called when a creative iframe load event fires.
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotOnload", (event) => {
  const slot = event.slot;
  console.log("Creative iframe for slot", slot.getSlotElementId(), "has loaded.");

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
См. также

googletag.events.SlotRenderEndedEvent

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
Deprecated.
line Item Id
Line item ID of the rendered reservation ad.
response Identifier
The response identifier is a unique identifier for the ad response.
service Name
Name of the service that triggered the event.
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 (legacy)

// This listener is called when a slot has finished rendering.
var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotRenderEnded", function (event) {
  var slot = event.slot;
  console.group("Slot", slot.getSlotElementId(), "finished rendering.");

  // Log details of the rendered ad.
  console.log("Advertiser ID:", event.advertiserId);
  console.log("Campaign ID:", event.campaignId);
  console.log("Company IDs:", event.companyIds);
  console.log("Creative ID:", event.creativeId);
  console.log("Creative Template ID:", event.creativeTemplateId);
  console.log("Is backfill?:", event.isBackfill);
  console.log("Is empty?:", event.isEmpty);
  console.log("Line Item ID:", event.lineItemId);
  console.log("Size:", event.size);
  console.log("Slot content changed?", event.slotContentChanged);
  console.log("Source Agnostic Creative ID:", event.sourceAgnosticCreativeId);
  console.log("Source Agnostic Line Item ID:", event.sourceAgnosticLineItemId);
  console.log("Yield Group IDs:", event.yieldGroupIds);
  console.groupEnd();

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});

Машинопись

// This listener is called when a slot has finished rendering.
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotRenderEnded", (event) => {
  const slot = event.slot;
  console.group("Slot", slot.getSlotElementId(), "finished rendering.");

  // Log details of the rendered ad.
  console.log("Advertiser ID:", event.advertiserId);
  console.log("Campaign ID:", event.campaignId);
  console.log("Company IDs:", event.companyIds);
  console.log("Creative ID:", event.creativeId);
  console.log("Creative Template ID:", event.creativeTemplateId);
  console.log("Is backfill?:", event.isBackfill);
  console.log("Is empty?:", event.isEmpty);
  console.log("Line Item ID:", event.lineItemId);
  console.log("Size:", event.size);
  console.log("Slot content changed?", event.slotContentChanged);
  console.log("Source Agnostic Creative ID:", event.sourceAgnosticCreativeId);
  console.log("Source Agnostic Line Item ID:", event.sourceAgnosticLineItemId);
  console.log("Yield Group IDs:", event.yieldGroupIds);
  console.groupEnd();

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
См. также

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


advertiserId

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

campaignId

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 (legacy)

// This listener is called when the specified service issues an ad
// request for a slot. Each slot will fire this event, even though they
// may be batched together in a single request if single request
// architecture (SRA) is enabled.
var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotRequested", function (event) {
  var slot = event.slot;
  console.log("Slot", slot.getSlotElementId(), "has been requested.");

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});

Машинопись

// This listener is called when the specified service issues an ad
// request for a slot. Each slot will fire this event, even though they
// may be batched together in a single request if single request
// architecture (SRA) is enabled.
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotRequested", (event) => {
  const slot = event.slot;
  console.log("Slot", slot.getSlotElementId(), "has been requested.");

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
См. также

googletag.events.SlotResponseReceived

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 (legacy)

// This listener is called when an ad response has been received
// for a slot.
var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotResponseReceived", function (event) {
  var slot = event.slot;
  console.log("Ad response for slot", slot.getSlotElementId(), "received.");

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});

Машинопись

// This listener is called when an ad response has been received
// for a slot.
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotResponseReceived", (event) => {
  const slot = event.slot;
  console.log("Ad response for slot", slot.getSlotElementId(), "received.");

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
См. также

googletag.events.SlotVisibilityChangedEvent

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 (legacy)

// This listener is called whenever the on-screen percentage of an
// ad slot's area changes.
var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotVisibilityChanged", function (event) {
  var slot = event.slot;
  console.group("Visibility of slot", slot.getSlotElementId(), "changed.");

  // Log details of the event.
  console.log("Visible area:", "".concat(event.inViewPercentage, "%"));
  console.groupEnd();

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});

Машинопись

// This listener is called whenever the on-screen percentage of an
// ad slot's area changes.
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotVisibilityChanged", (event) => {
  const slot = event.slot;
  console.group("Visibility of slot", slot.getSlotElementId(), "changed.");

  // Log details of the event.
  console.log("Visible area:", `${event.inViewPercentage}%`);
  console.groupEnd();

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
См. также

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


inViewPercentage

inViewPercentage : 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 (legacy)

// id is provided
googletag.secureSignalProviders.push({
  id: "collector123",
  collectorFunction: function () {
    // ...custom signal generation logic...
    return Promise.resolve("signal");
  },
});

Машинопись

// id is provided
googletag.secureSignalProviders!.push({
  id: "collector123",
  collectorFunction: () => {
    // ...custom signal generation logic...
    return Promise.resolve("signal");
  },
});
См. также

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


collectorFunction

collectorFunction : ( ( ) => Promise < string > )
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 (legacy)

// networkCode is provided
googletag.secureSignalProviders.push({
  networkCode: "123456",
  collectorFunction: function () {
    // ...custom signal generation logic...
    return Promise.resolve("signal");
  },
});

Машинопись

// networkCode is provided
googletag.secureSignalProviders!.push({
  networkCode: "123456",
  collectorFunction: () => {
    // ...custom signal generation logic...
    return Promise.resolve("signal");
  },
});
См. также

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


collectorFunction

collectorFunction : ( ( ) => Promise < string > )
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.