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 是一个接受函数的 剩余形参 。剩余形参接受指定类型的任意数量的值。

googletag

Google 发布商代码用于其 API 的全局命名空间。
命名空间
config
用于页面级设置的主要配置界面。
enums
这是 GPT 用于枚举类型的命名空间。
events
这是 GPT 用于事件的命名空间。
secureSignals
这是 GPT 用于管理安全信号的命名空间。
接口
CommandArray
命令数组接受一系列函数,并按顺序调用这些函数。
CompanionAdsService
随播广告服务。
PrivacySettingsConfig
隐私设置的配置对象。
PubAdsService
发布商广告服务。
ResponseInformation
表示单个广告响应的对象。
RewardedPayload
表示与激励广告关联的奖励的对象。
Service
包含所有服务通用方法的基服务类。
SizeMappingBuilder
用于尺寸映射规范对象的构建器。
Slot
Slot 是一个对象,表示网页上的单个广告位。
类型别名
GeneralSize
相应广告位的有效尺寸配置,可以是一种或多种尺寸。
MultiSize
单个有效尺寸的列表。
NamedSize
广告资源位可以具有的命名尺寸。
SingleSize
一个有效的广告资源尺寸。
SingleSizeArray
包含两个数字的数组,表示 [宽度,高度]。
SizeMapping
视口尺寸与广告尺寸的映射。
SizeMappingArray
尺寸映射的列表。
变量
apiReady
标志,用于指示 GPT API 是否已加载并可供调用。
cmd
对全局命令队列的引用,用于异步执行与 GPT 相关的调用。
pubadsReady
标志,用于指示 PubAdsService 是否已启用、加载并完全正常运行。
secureSignalProviders
对安全信号提供商数组的引用。
函数
companionAds
返回对 CompanionAdsService 的引用。
defineOutOfPageSlot
使用指定广告单元路径构建页外广告位。
defineSlot
使用给定的广告单元路径和尺寸构建广告位,并将其与网页上将包含广告的 div 元素的 ID 相关联。
destroySlots
销毁给定的 slot,从 GPT 中移除这些 slot 的所有相关对象和引用。
disablePublisherConsole
停用 Google 发布商控制台。
display
指示 slot 服务呈现 slot。
enableServices
启用已为网页上的广告位定义的所有 GPT 服务。
getConfig
获取由 setConfig 设置的网页的一般配置选项。
getVersion
返回当前 GPT 版本。
openConsole
打开 Google 发布商控制台。
pubads
返回对 PubAdsService 的引用。
setAdIframeTitle
从这一刻起,为 PubAdsService 创建的所有广告容器 iframe 设置标题。
setConfig
设置网页的常规配置选项。
sizeMapping
创建新的 SizeMappingBuilder

类型别名


GeneralSize

GeneralSize: SingleSize | MultiSize
相应广告位的有效尺寸配置,可以是一种或多种尺寸。

MultiSize

MultiSize: SingleSize[]
单个有效尺寸的列表。

NamedSize

NamedSize: "fluid" | ["fluid"]
广告资源位可以具有的命名尺寸。在大多数情况下,大小是一个固定大小的矩形,但在某些情况下,我们需要其他类型的大小规范。只有以下命名尺寸有效:
  • 自适应:广告容器的宽度为父 div 的 100%,然后调整其高度以适应广告素材内容。与网页上常规块元素的行为类似。用于原生广告(请参阅相关文章)。请注意,fluid['fluid'] 都是声明广告资源尺寸为自适应尺寸的可接受形式。

SingleSize

一个有效的广告资源尺寸。

SingleSizeArray

SingleSizeArray: [number, number]
包含两个数字的数组,表示 [宽度,高度]。

SizeMapping

视口尺寸与广告尺寸的映射。用于自适应广告。

SizeMappingArray

SizeMappingArray: SizeMapping[]
尺寸映射的列表。

变量


Const apiReady

apiReady: boolean | undefined
标志,用于指示 GPT API 是否已加载并可供调用。在 API 准备就绪之前,此属性将仅为 undefined

请注意,处理异步操作的推荐方式是使用 googletag.cmd 来为 GPT 准备就绪时排队回调。这些回调不必检查 googletag.apiReady,因为它们保证在 API 设置完毕后执行。

Const cmd

cmd: ((this: typeof globalThis) => void)[] | CommandArray
对全局命令队列的引用,用于异步执行与 GPT 相关的调用。

googletag.cmd 变量由网页上的 GPT 代码语法初始化为一个空的 JavaScript 数组,而 cmd.push 是将元素添加到数组末尾的标准 Array.push 方法。当 GPT JavaScript 加载时,它会遍历该数组并按顺序执行所有函数。然后,脚本会将 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());
});

TypeScript

googletag.cmd.push(() => {
  googletag.defineSlot("/1234567/sports", [160, 600])!.addService(googletag.pubads());
});

Const pubadsReady

pubadsReady: boolean | undefined
标志,用于指示 PubAdsService 是否已启用、加载并完全正常运行。在调用 enableServicesPubAdsService 加载并初始化之前,此属性将仅为 undefined

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");
  },
});

TypeScript

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 元素的 ID。如需了解详情,请参阅有关页外广告素材的文章。

对于由 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);

TypeScript

// Define a custom out-of-page ad slot.
googletag.defineOutOfPageSlot("/1234567/sports", "div-1");

// Define a GPT managed web interstitial ad slot.
googletag.defineOutOfPageSlot("/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL);
另请参阅
参数
adUnitPath: string包含广告资源网代码和广告单元代码的完整广告单元路径
Optional div: string | OutOfPageFormat将包含相应广告单元或 OutOfPageFormat 的 div 的 ID。
返回
Slot | null新创建的 slot;如果无法创建 slot,则为 null

defineSlot

defineSlot(adUnitPath: string, size: GeneralSize, div?: string): Slot | null
使用给定的广告单元路径和尺寸构建广告位,并将其与网页上将包含广告的 div 元素的 ID 相关联。
示例

JavaScript

googletag.defineSlot("/1234567/sports", [728, 90], "div-1");

JavaScript(旧版)

googletag.defineSlot("/1234567/sports", [728, 90], "div-1");

TypeScript

googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
另请参阅
参数
adUnitPath: string包含广告资源网代码和广告单元代码的完整广告单元路径
size: GeneralSize所添加广告位的宽度和高度。如果未提供自适应尺寸映射,或者视口尺寸小于映射中提供的最小尺寸,则广告请求中使用此尺寸。
Optional div: string将包含相应广告单元的 div 的 ID。
返回
Slot | null新创建的 slot;如果无法创建 slot,则为 null

destroySlots

destroySlots(slots?: Slot[]): boolean
销毁给定的 slot,从 GPT 中移除这些 slot 的所有相关对象和引用。此 API 不支持回传广告位和随播广告位。

对广告位调用此 API 会清除广告,并从 GPT 维护的内部状态中移除广告位对象。对 slot 对象调用任何其他函数都会导致未定义的行为。请注意,如果发布商网页保留了对该 slot 的引用,浏览器可能仍不会释放与该 slot 关联的内存。调用此 API 会使与相应广告位关联的 div 可供重复使用。

具体而言,销毁广告位会从 GPT 的长期存在的网页浏览中移除相应广告,因此未来的请求不会受到涉及此广告的阻碍广告或竞争性排除设置的影响。如果在从网页中移除 slot 的 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();

TypeScript

// The calls to construct an ad and display contents.
const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!;
googletag.display("div-1");
const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!;
googletag.display("div-2");

// This call to destroy only slot1.
googletag.destroySlots([slot1]);

// This call to destroy both slot1 and slot2.
googletag.destroySlots([slot1, slot2]);

// This call to destroy all slots.
googletag.destroySlots();
参数
Optional slots: Slot[]要摧毁的格子的数组。数组是可选的;如果未指定,则所有槽都会被销毁。
返回
boolean如果槽位已被销毁,则为 true;否则为 false

disablePublisherConsole

disablePublisherConsole(): void
停用 Google 发布商控制台。
另请参阅

显示

display(divOrSlot: string | Element | Slot): void
指示 slot 服务呈现 slot。每个广告位在每个网页上只能展示一次。所有广告资源位都必须先经过定义并与服务相关联,然后才能显示。在元素出现在 DOM 中之前,不得进行显示调用。实现此目的的常用方法是将该代码放置在方法调用中指定的 div 元素内的脚本块中。

如果使用单一请求架构 (SRA),则在调用此方法时,所有尚未提取的广告位都将一次性提取。如需强制广告展示位置不展示广告,必须移除整个 div。
另请参阅
参数
divOrSlot: string | Element | Slot包含广告位的 div 元素的 ID 或 div 元素本身,或者广告位对象。如果提供了 div 元素,则该元素必须具有与传递到 defineSlot 中的 ID 相匹配的“id”属性。

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"]);

TypeScript

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

// Get the value of the `adsenseAttributes` and `disableInitialLoad` settings.
const config = googletag.getConfig(["adsenseAttributes", "disableInitialLoad"]);
参数
keys: string | string[]要获取的配置选项的键。
返回
Pick<PageSettingsConfig, "adsenseAttributes" | "disableInitialLoad" | "targeting">相应 slot 的配置选项。

getVersion

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

TypeScript

// Calling with div ID.
googletag.openConsole("div-1");

// Calling without div ID.
googletag.openConsole();
另请参阅
参数
Optional div: string广告位 div ID。此值为可选值。如果提供此参数,发布商控制台将尝试打开,并显示指定广告展示位置的详细信息。

pubads

pubads(): PubAdsService
返回对 PubAdsService 的引用。
返回
PubAdsService发布商广告服务。

setAdIframeTitle

setAdIframeTitle(title: string): void
从这一刻起,为 PubAdsService 创建的所有广告容器 iframe 设置标题。
示例

JavaScript

googletag.setAdIframeTitle("title");

JavaScript(旧版)

googletag.setAdIframeTitle("title");

TypeScript

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());
});

TypeScript

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
随播广告服务。此服务由视频广告用于展示随播广告。
方法
addEventListener
注册一个监听器,以便您在网页上发生特定 GPT 事件时设置并调用 JavaScript 函数。
getSlots
获取与此服务关联的 slot 列表。
removeEventListener
移除之前注册的监听器。
setRefreshUnfilledSlots
设置是否自动补余尚未填充的随播广告位。
另请参阅

方法


setRefreshUnfilledSlots

setRefreshUnfilledSlots(value: boolean): void
设置是否自动补余尚未填充的随播广告位。

此方法可在网页的生命周期内多次调用,以开启和关闭补余功能。只有也向 PubAdsService 注册的广告位才会进行补余。由于政策限制,此方法在投放 Ad Exchange 视频时不会填充空的随播广告位。
示例

JavaScript

googletag.companionAds().setRefreshUnfilledSlots(true);

JavaScript(旧版)

googletag.companionAds().setRefreshUnfilledSlots(true);

TypeScript

googletag.companionAds().setRefreshUnfilledSlots(true);
参数
value: booleantrue 表示自动回填未填充的广告资源块,false 表示保持不变。

googletag.PrivacySettingsConfig

隐私设置的配置对象。
属性
childDirectedTreatment?
表示相应网页是否应视为面向儿童的内容
limitedAds?
启用在受限广告模式下运行的投放,以帮助发布商满足法规遵从需求。
nonPersonalizedAds?
启用投放功能以在非个性化广告模式下运行,从而帮助发布商满足法规遵从需求。
restrictDataProcessing?
使投放在受限处理模式下运行,以帮助发布商满足法规遵从需求。
trafficSource?
指明请求代表的是付费流量还是自然流量。
underAgeOfConsent?
用于指明是否将广告请求标记为来自未达到法定承诺年龄的用户的请求。
另请参阅

属性


Optional childDirectedTreatment

childDirectedTreatment?: boolean
指示相应网页是否应视为面向儿童的内容。设置为 null 可清除配置。

Optional limitedAds

limitedAds?: boolean
启用投放功能以在受限广告模式下运行,从而帮助发布商满足监管合规性要求。

您可以通过以下两种方式指示 GPT 请求受限广告:
  • 自动,通过使用 IAB TCF v2.0 意见征求管理平台中的信号。
  • 手动设置,即将此字段的值设置为 true
只有在从受限广告网址加载 GPT 时,才能手动配置受限广告。如果尝试在从标准网址加载 GPT 后修改此设置,系统会生成发布商控制台警告

请注意,使用 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,
});

TypeScript

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

nonPersonalizedAds?: boolean
启用投放功能以在非个性化广告模式下运行,从而帮助发布商满足法规遵从需求。

Optional restrictDataProcessing

restrictDataProcessing?: boolean
使投放在受限处理模式下运行,以帮助发布商满足法规遵从需求。

Optional trafficSource

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,
});

TypeScript

// Indicate requests represent organic traffic.
googletag.pubads().setPrivacySettings({
  trafficSource: googletag.enums.TrafficSource.ORGANIC,
});

// Indicate requests represent purchased traffic.
googletag.pubads().setPrivacySettings({
  trafficSource: googletag.enums.TrafficSource.PURCHASED,
});

Optional underAgeOfConsent

underAgeOfConsent?: boolean
用于指明是否将广告请求标记为来自未达到法定承诺年龄的用户的请求。设置为 null 可清除配置。

googletag.PubAdsService

扩展 Service
发布商广告服务。此服务用于从您的 Google Ad Manager 账号中提取和展示广告。
方法
addEventListener
注册一个监听器,以便您在网页上发生特定 GPT 事件时设置并调用 JavaScript 函数。
clear
从指定 slot 中移除广告,并将其替换为空内容。
clearCategoryExclusions
已弃用。 清除所有网页级广告类别排除标签。
clearTargeting
已弃用。 清除特定键或所有键的自定义定位参数。
collapseEmptyDivs
已弃用。 启用后,系统会在没有要显示的广告内容时合拢广告位 div,使其不会占用网页上的任何空间。
disableInitialLoad
已弃用。 在网页加载时停用广告请求,但允许通过 PubAdsService.refresh 调用请求广告。
display
使用给定的广告单元路径和尺寸构建并显示广告位。
enableLazyLoad
已弃用。 根据配置对象中定义的设置,在 GPT 中启用延迟加载。
enableSingleRequest
已弃用。 启用单次请求模式,以便同时提取多个广告。
enableVideoAds
已弃用。 向 GPT 发出信号,表明网页上将显示视频广告。
get
已弃用。 返回与给定键相关联的 AdSense 属性的值。
getAttributeKeys
已弃用。 返回已在此服务上设置的属性键。
getSlots
获取与此服务关联的 slot 列表。
getTargeting
已弃用。 返回已设置的特定自定义服务级定位参数。
getTargetingKeys
已弃用。 返回已设置的所有自定义服务级定位键的列表。
isInitialLoadDisabled
已弃用。 返回之前通过 PubAdsService.disableInitialLoad 调用是否成功停用了初始广告请求。
refresh
提取并显示网页上特定或所有广告位的新广告。
removeEventListener
移除之前注册的监听器。
set
已弃用。 为适用于发布商广告服务下所有广告位的 AdSense 属性设置值。
setCategoryExclusion
已弃用。 为指定标签名称设置页面级广告类别排除。
setCentering
已弃用。 启用和停用广告的水平居中。
setForceSafeFrame
已弃用。 配置是否应强制网页上的所有广告使用 SafeFrame 容器呈现。
setLocation
已弃用。 传递网站的位置信息,以便您将订单项定位到特定地理位置。
setPrivacySettings
允许使用配置对象通过单个 API 配置所有隐私设置。
setPublisherProvidedId
设置发布商提供的 ID 的值。
setSafeFrameConfig
已弃用。 为 SafeFrame 配置设置网页级偏好设置。
setTargeting
已弃用。 为指定键设置自定义定位参数,这些参数适用于所有 Publisher Ads 服务广告位。
setVideoContent
已弃用。 设置要随广告请求一起发送的视频内容信息,以用于定位和排除内容。
updateCorrelator
更改随广告请求发送的相关性标识符,从而有效地开始新的网页浏览。

方法


清除

clear(slots?: Slot[]): boolean
从指定 slot 中移除广告,并将其替换为空内容。相应展示位置将被标记为未提取。

具体而言,清除展示位置会从 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();

TypeScript

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

// This call to clear only slot1.
googletag.pubads().clear([slot1]);

// This call to clear both slot1 and slot2.
googletag.pubads().clear([slot1, slot2]);

// This call to clear all slots.
googletag.pubads().clear();
参数
Optional slots: Slot[]要清除的 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.

TypeScript

// Set category exclusion to exclude ads with 'AirlineAd' labels.
googletag.pubads().setCategoryExclusion("AirlineAd");

// Make ad requests. No ad with 'AirlineAd' label will be returned.

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

// Make ad requests. Any ad can be returned.
另请参阅
返回
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.

TypeScript

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

googletag.pubads().clearTargeting("interests");
// Targeting 'colors' and 'fruits' are still present, while 'interests'
// was cleared.

googletag.pubads().clearTargeting();
// All targeting has been cleared.
另请参阅
参数
Optional key: string定位参数键。此键是可选的;如果未指定,系统将清除所有定位参数。
返回
PubAdsService调用方法的服务对象。

collapseEmptyDivs

collapseEmptyDivs(collapseBeforeAdFetch?: boolean): boolean
启用广告位 div 的合拢功能,以便在没有要显示的广告内容时,广告位 div 不会占用网页上的任何空间。必须在启用服务之前设置此模式。
另请参阅
参数
Optional collapseBeforeAdFetch: boolean是否在获取广告之前就合拢广告位。此参数为可选参数;如果未提供,则将使用 false 作为默认值。
返回
boolean如果已启用 div 收起模式,则返回 true;如果无法启用收起模式(因为在启用服务后调用了该方法),则返回 false

disableInitialLoad

disableInitialLoad(): void
在网页加载时停用广告请求,但允许通过 PubAdsService.refresh 调用请求广告。应在启用服务之前设置此参数。必须使用异步模式;否则,将无法使用 refresh 请求广告。
另请参阅

显示

display(adUnitPath: string, size: GeneralSize, div?: string | Element, clickUrl?: string): void
使用给定的广告单元路径和尺寸构建并显示广告位。此方法不适用于单次请求模式。

注意:调用此方法时,系统会创建 slot 和页面状态的快照,以确保在发送广告请求和呈现响应时保持一致性。在此方法调用后对 slot 或网页状态所做的任何更改(包括定位、隐私权设置、强制使用 SafeFrame 等)都只会应用于后续的 display()refresh() 请求。
示例

JavaScript

googletag.pubads().display("/1234567/sports", [728, 90], "div-1");

JavaScript(旧版)

googletag.pubads().display("/1234567/sports", [728, 90], "div-1");

TypeScript

googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
另请参阅
参数
adUnitPath: string要渲染的广告位的广告单元路径
size: GeneralSize广告位的宽度和高度。
Optional div: string | Element包含广告位的 div 的 ID 或 div 元素本身。
Optional clickUrl: string要在相应广告资源块上使用的点击跟踪网址。

enableLazyLoad

enableLazyLoad(config?: {
  fetchMarginPercent?: number;
  mobileScaling?: number;
  renderMarginPercent?: number;
}): void
根据配置对象中的定义,在 GPT 中启用延迟加载。如需查看更详细的示例,请参阅延迟加载示例。

注意:只有当所有 slot 都位于提取边距之外时,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,
});

TypeScript

googletag.pubads().enableLazyLoad({
  // Fetch slots within 5 viewports.
  fetchMarginPercent: 500,
  // Render slots within 2 viewports.
  renderMarginPercent: 200,
  // Double the above values on mobile.
  mobileScaling: 2.0,
});
另请参阅
参数
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

enableVideoAds(): void
向 GPT 发出信号,表明网页上将显示视频广告。这样,就可以对展示广告和视频广告应用竞争排除限制。如果视频内容已知,请调用 PubAdsService.setVideoContent,以便能够使用展示广告的内容排除功能。

get

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'.

TypeScript

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'].

TypeScript

googletag.pubads().set("adsense_background_color", "#FFFFFF");
googletag.pubads().set("adsense_border_color", "#AABBCC");
googletag.pubads().getAttributeKeys();
// Returns ['adsense_background_color', 'adsense_border_color'].
返回
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).

TypeScript

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'].

TypeScript

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

googletag.pubads().getTargetingKeys();
// Returns ['interests', 'colors'].
返回
string[]定位键数组。顺序未定义。

isInitialLoadDisabled

isInitialLoadDisabled(): boolean
返回之前通过 PubAdsService.disableInitialLoad 调用是否成功停用了初始广告请求。
返回
boolean如果之前对 PubAdsService.disableInitialLoad 的调用成功,则返回 true;否则,返回 false

刷新

refresh(slots?: Slot[], options?: {
  changeCorrelator: boolean;
}): void
提取并显示网页上特定或所有广告位的新广告。仅在异步呈现模式下有效。

为了在所有浏览器中实现适当的行为,调用 refresh 之前必须先调用广告展示位置的 display。如果省略对 display 的调用,刷新可能会出现意外行为。如果需要,可以使用 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 });

TypeScript

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

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

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

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

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

// This call to refresh fetches a new ad for each slot, without
// changing the correlator.
googletag.pubads().refresh(null, { changeCorrelator: false });
另请参阅
参数
Optional slots: Slot[]要刷新的 slot。数组是可选的;如果未指定,则会刷新所有 slot。
Optional options: {
  changeCorrelator: boolean;
}
与此刷新调用相关联的配置选项。
  • changeCorrelator

    指定是否为提取广告生成新的相关性标识符。我们的广告服务器会短暂地(目前为 30 秒,但可能会发生变化)保留此相关性标识符值,这样一来,如果收到具有相同相关性标识符值的请求的时间非常接近,这些请求就会被视为一次网页浏览。默认情况下,每次刷新都会生成一个新的相关性标识符。

    注意:此选项对 GPT 的长期存在的网页浏览没有影响,该网页浏览会自动反映网页上当前的广告,并且没有过期时间。

设置

set(key: string, value: string): PubAdsService
为适用于 Publisher Ads 服务下所有广告位的 AdSense 属性设置值。

针对同一键多次调用此方法会覆盖之前为该键设置的值。必须先设置所有值,然后才能调用 displayrefresh
示例

JavaScript

googletag.pubads().set("adsense_background_color", "#FFFFFF");

JavaScript(旧版)

googletag.pubads().set("adsense_background_color", "#FFFFFF");

TypeScript

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");

TypeScript

// Label = AirlineAd.
googletag.pubads().setCategoryExclusion("AirlineAd");
另请参阅
参数
categoryExclusion: string要添加的广告类别排除标签。
返回
PubAdsService调用方法的服务对象。

setCentering

setCentering(centerAds: boolean): void
启用和停用广告的水平居中。居中功能默认处于停用状态。在旧版 gpt_mobile.js 中,居中功能默认处于启用状态。

此方法应在调用 displayrefresh 之前调用,因为只有在调用此方法之后请求的广告才会居中。
示例

JavaScript

// Make ads centered.
googletag.pubads().setCentering(true);

JavaScript(旧版)

// Make ads centered.
googletag.pubads().setCentering(true);

TypeScript

// Make ads centered.
googletag.pubads().setCentering(true);
参数
centerAds: booleantrue 可将广告居中放置,false 可将广告靠左对齐。

setForceSafeFrame

setForceSafeFrame(forceSafeFrame: boolean): PubAdsService
配置是否应强制使用 SafeFrame 容器呈现网页上的所有广告。

使用此 API 时,请注意以下事项:
  • 此设置仅对相应广告位的后续广告请求生效。
  • 如果指定了广告位级设置,则该设置始终会覆盖网页级设置。
  • 如果设置为 true(在广告位级或网页级),无论在 Google Ad Manager 界面中做出何种选择,广告都将始终使用 SafeFrame 容器呈现。
  • 不过,如果设置为 false 或保持未指定,系统将使用 SafeFrame 容器呈现广告,具体取决于广告素材类型和 Google Ad Manager 界面中的选择。
  • 此 API 应谨慎使用,因为它可能会影响尝试脱离其 iframe 或依赖于直接在发布商网页中呈现的广告素材的行为。
示例

JavaScript

googletag.pubads().setForceSafeFrame(true);

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

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

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

JavaScript(旧版)

googletag.pubads().setForceSafeFrame(true);

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

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

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

TypeScript

googletag.pubads().setForceSafeFrame(true);

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

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

googletag.display("div-1");
googletag.display("div-2");
另请参阅
参数
forceSafeFrame: booleantrue 可强制将网页上的所有广告呈现在 SafeFrame 中,而 false 可将之前的设置更改为 false。如果之前未指定此值,则将其设置为 false 不会产生任何变化。
返回
PubAdsService调用方法的服务对象。

setLocation

setLocation(address: string): PubAdsService
传递网站中的地理位置信息,以便您可以针对特定地理位置定位广告订单项。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

// 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,
});

TypeScript

googletag.pubads().setPrivacySettings({
  restrictDataProcessing: true,
});

// Set multiple privacy settings at the same time.
googletag.pubads().setPrivacySettings({
  childDirectedTreatment: true,
  underAgeOfConsent: true,
});

// Clear the configuration for childDirectedTreatment.
googletag.pubads().setPrivacySettings({
  childDirectedTreatment: null,
});
另请参阅
参数
privacySettings: PrivacySettingsConfig包含隐私设置配置的对象。
返回
PubAdsService调用函数的服务对象。

setPublisherProvidedId

setPublisherProvidedId(ppid: string): PubAdsService
设置发布商提供的 ID 的值。
示例

JavaScript

googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");

JavaScript(旧版)

googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");

TypeScript

googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
另请参阅
参数
ppid: string发布商提供的字母数字 ID。长度必须介于 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");

TypeScript

googletag.pubads().setForceSafeFrame(true);

const pageConfig = {
  allowOverlayExpansion: true,
  allowPushExpansion: true,
  sandbox: true,
};

const slotConfig = { allowOverlayExpansion: false };

googletag.pubads().setSafeFrameConfig(pageConfig);

// The following slot will not allow for expansion by overlay.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")!
  .setSafeFrameConfig(slotConfig)
  .addService(googletag.pubads());

// The following slot will inherit the page level settings, and hence
// would allow for expansion by overlay.
googletag.defineSlot("/1234567/news", [160, 600], "div-2")!.addService(googletag.pubads());

googletag.display("div-1");
googletag.display("div-2");
另请参阅
参数
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"]);

TypeScript

// Example with a single value for a key.
googletag.pubads().setTargeting("interests", "sports");

// Example with multiple values for a key inside in an array.
googletag.pubads().setTargeting("interests", ["sports", "music"]);
另请参阅
参数
key: string定位参数键。
value: string | string[]定位参数值或值数组。
返回
PubAdsService调用方法的服务对象。

setVideoContent

setVideoContent(videoContentId: string, videoCmsId: string): void
设置要随广告请求一起发送的视频内容信息,以用于定位和内容排除。调用此方法时,系统会自动启用视频广告。对于 videoContentIdvideoCmsId,请使用提供给 Google Ad Manager 内容提取服务的值。
另请参阅
参数
videoContentId: string视频内容 ID。
videoCmsId: string视频 CMS ID。

updateCorrelator

updateCorrelator(): PubAdsService
更改随广告请求发送的相关性标识符,从而有效地开始新的网页浏览。源于同一次网页浏览的所有广告请求会共用一个 correlator 值;但针对每次网页浏览,这个值都是独一无二的。仅适用于异步模式。

注意:此方法对 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.

TypeScript

// Assume that the correlator is currently 12345. All ad requests made
// by this page will currently use that value.

// Replace the current correlator with a new correlator.
googletag.pubads().updateCorrelator();

// The correlator will now be a new randomly selected value, different
// from 12345. All subsequent ad requests made by this page will use
// the new value.
返回
PubAdsService调用函数的服务对象。

googletag.ResponseInformation

表示单个广告响应的对象。
属性
advertiserId
广告客户的 ID。
campaignId
广告系列的 ID。
creativeId
相应广告素材的 ID。
creativeTemplateId
广告的模板 ID。
lineItemId
相应订单项的 ID。
另请参阅

属性


advertiserId

advertiserId: number
广告客户的 ID。

campaignId

campaignId: number
广告系列的 ID。

creativeId

creativeId: number
相应广告素材的 ID。

creativeTemplateId

creativeTemplateId: number
广告的模板 ID。

lineItemId

lineItemId: number
相应订单项的 ID。

googletag.RewardedPayload

表示与激励广告关联的奖励的对象
属性
amount
奖励中包含的商品数量。
type
奖励中包含的商品类型(例如“coin”)。
另请参阅

属性


金额

amount: number
奖励中包含的商品数量。

type

type: string
奖励中包含的商品类型(例如“coin”)。

googletag.Service

包含所有服务通用方法的基服务类。
方法
addEventListener
注册一个监听器,以便您在网页上发生特定 GPT 事件时设置并调用 JavaScript 函数。
getSlots
获取与此服务关联的 slot 列表。
removeEventListener
移除之前注册的监听器。

方法


addEventListener

addEventListener<K extends keyof EventTypeMap>(eventType: K, listener: ((arg: EventTypeMap[K]) => void)): Service
注册一个监听器,以便您在网页上发生特定 GPT 事件时设置并调用 JavaScript 函数。支持以下事件:当调用监听器时,系统会向其传递相应事件类型的对象。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

// 2. Adding an event listener with slot specific logic.
// Listeners operate at service level, which means that you cannot add
// a listener for an event for a specific slot only. You can, however,
// programmatically filter a listener to respond only to a certain ad
// slot, using this pattern:
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotOnload", (event) => {
  if (event.slot === targetSlot) {
    // Slot specific logic.
  }
});
另请参阅
参数
eventType: K一个字符串,表示由 GPT 生成的事件的类型。事件类型区分大小写。
listener: ((arg: EventTypeMap[K]) => void)接受单个事件对象实参的函数。
返回
Service调用方法的服务对象。

getSlots

getSlots(): Slot[]
获取与此服务关联的 slot 列表。
返回
Slot[]广告资源位在添加到服务中的顺序。

removeEventListener

removeEventListener<K extends keyof EventTypeMap>(eventType: K, listener: ((event: EventTypeMap[K]) => void)): void
移除之前注册的监听器。
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

  // Add onViewableListener as a listener for impressionViewable events.
  googletag.pubads().addEventListener("impressionViewable", onViewableListener);
  googletag.enableServices();
});
参数
eventType: K一个字符串,表示由 GPT 生成的事件的类型。事件类型区分大小写。
listener: ((event: EventTypeMap[K]) => void)接受单个事件对象实参的函数。

googletag.SizeMappingBuilder

用于尺寸映射规范对象的构建器。此构建器旨在帮助您轻松构建尺寸规范。
方法
addSize
添加从单尺寸数组(表示视口)到单尺寸或多尺寸数组(表示广告位)的映射。
build
根据添加到此构建器的映射构建尺寸地图规范。
另请参阅

方法


addSize

addSize(viewportSize: SingleSizeArray, slotSize: GeneralSize): SizeMappingBuilder
添加从单尺寸数组(表示视口)到单尺寸或多尺寸数组(表示 slot)的映射。
示例

JavaScript

// Mapping 1
googletag
  .sizeMapping()
  .addSize([1024, 768], [970, 250])
  .addSize([980, 690], [728, 90])
  .addSize([640, 480], "fluid")
  .addSize([0, 0], [88, 31]) // All viewports &lt; 640x480
  .build();

// Mapping 2
googletag
  .sizeMapping()
  .addSize([1024, 768], [970, 250])
  .addSize([980, 690], [])
  .addSize([640, 480], [120, 60])
  .addSize([0, 0], [])
  .build();

// Mapping 2 will not show any ads for the following viewport sizes:
// [1024, 768] > size >= [980, 690] and
// [640, 480] > size >= [0, 0]

JavaScript(旧版)

// Mapping 1
googletag
  .sizeMapping()
  .addSize([1024, 768], [970, 250])
  .addSize([980, 690], [728, 90])
  .addSize([640, 480], "fluid")
  .addSize([0, 0], [88, 31]) // All viewports &lt; 640x480
  .build();

// Mapping 2
googletag
  .sizeMapping()
  .addSize([1024, 768], [970, 250])
  .addSize([980, 690], [])
  .addSize([640, 480], [120, 60])
  .addSize([0, 0], [])
  .build();

// Mapping 2 will not show any ads for the following viewport sizes:
// [1024, 768] > size >= [980, 690] and
// [640, 480] > size >= [0, 0]

TypeScript

// Mapping 1
googletag
  .sizeMapping()
  .addSize([1024, 768], [970, 250])
  .addSize([980, 690], [728, 90])
  .addSize([640, 480], "fluid")
  .addSize([0, 0], [88, 31]) // All viewports &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相应映射条目的视口大小。
slotSize: GeneralSize相应映射条目的广告位的尺寸。
返回
SizeMappingBuilder对此构建器的引用。

build

build(): SizeMappingArray
根据添加到此构建器的映射构建尺寸映射规范。

如果提供了任何无效的映射,此方法将返回 null。否则,它会返回正确格式的规范,以传递给 Slot.defineSizeMapping

注意:调用此方法后,构建器的行为未定义。
返回
SizeMappingArray此构建器构建的结果。如果提供的尺寸映射无效,则可以为 null。

googletag.Slot

Slot 是一个对象,表示网页上的单个广告位。
方法
addService
向此 slot 添加 Service
clearCategoryExclusions
已弃用。 清除相应广告位的所有广告位级广告类别排除标签。
clearTargeting
已弃用。 清除相应 slot 的特定或所有自定义 slot 级定位参数。
defineSizeMapping
为相应 slot 设置从最小视口大小到 slot 大小的映射数组。
get
已弃用。 返回与相应广告位的给定键相关联的 AdSense 属性的值。
getAdUnitPath
返回广告单元的完整路径,包括广告资源网代码和广告单元路径。
getAttributeKeys
已弃用。 返回为此 slot 设置的属性键的列表。
getCategoryExclusions
已弃用。 返回相应广告位的广告类别排除标签。
getConfig
获取由 setConfig 设置的 slot 的常规配置选项。
getResponseInformation
返回广告响应信息。
getSlotElementId
返回定义 slot 时提供的 slot ID div
getTargeting
已弃用。 返回在此 slot 上设置的特定自定义定位参数。
getTargetingKeys
已弃用。 返回为此广告资源位设置的所有自定义定位键的列表。
set
已弃用。 为相应广告位上的 AdSense 属性设置值。
setCategoryExclusion
已弃用。 在此广告位上设置广告位级广告类别排除标签。
setClickUrl
已弃用。 设置用户点击广告后会被重定向到的点击跟踪网址。
setCollapseEmptyDiv
已弃用。  设置在广告位中没有广告时是否应隐藏该广告位 div
setConfig
为此 slot 设置常规配置选项。
setForceSafeFrame
已弃用。 配置是否应强制使用 SafeFrame 容器呈现此广告位中的广告。
setSafeFrameConfig
已弃用。 为 SafeFrame 配置设置 slot 级偏好设置。
setTargeting
已弃用。 为此 slot 设置自定义定位参数。
updateTargetingFromMap
已弃用。 根据 JSON 对象中的键值对映射,为此广告资源位设置自定义定位参数。

方法


addService

addService(service: Service): Slot
向相应 slot 添加服务
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

googletag.defineSlot("/1234567/sports", [160, 600], "div")!.addService(googletag.pubads());
另请参阅
参数
service: Service要添加的服务。
返回
Slot调用方法的 slot 对象。

clearCategoryExclusions

clearCategoryExclusions(): Slot
清除相应广告位的所有广告位级广告类别排除标签。
示例

JavaScript

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

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

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

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

JavaScript(旧版)

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

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

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

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

TypeScript

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

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

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

// Make an ad request. Any ad can be returned for the slot.
返回
Slot调用方法的 slot 对象。

clearTargeting

clearTargeting(key?: string): Slot
清除相应广告位的特定或所有自定义广告位级定位参数。
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

slot.clearTargeting();
// All targeting has been cleared.
另请参阅
参数
Optional key: string定位参数键。此键是可选的;如果未指定,系统将清除所有定位参数。
返回
Slot调用方法的 slot 对象。

defineSizeMapping

defineSizeMapping(sizeMapping: SizeMappingArray): Slot
为相应广告资源位设置从最小视口尺寸到广告资源位尺寸的映射数组。
示例

JavaScript

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

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

slot.defineSizeMapping(mapping);

JavaScript(旧版)

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

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

slot.defineSizeMapping(mapping);

TypeScript

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

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

slot.defineSizeMapping(mapping!);
另请参阅
参数
sizeMapping: SizeMappingArray尺寸映射的数组。您可以使用 SizeMappingBuilder 来创建它。每个尺寸映射都是一个包含两个元素的数组:SingleSizeArrayGeneralSize
返回
Slot调用方法的 slot 对象。

get

get(key: string): string
返回与相应广告位的给定键相关联的 AdSense 属性的值。如需查看此广告位继承的服务级属性,请使用 PubAdsService.get
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

slot.get("adsense_background_color");
// Returns '#FFFFFF'.
另请参阅
参数
key: string要查找的属性的名称。
返回
string属性键的当前值;如果不存在该键,则返回 null

getAdUnitPath

getAdUnitPath(): string
返回广告单元的完整路径,包括广告资源网代码和广告单元路径。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

slot.getAdUnitPath();
// Returns '/1234567/sports'.
返回
string广告单元路径。

getAttributeKeys

getAttributeKeys(): string[]
返回此 slot 上设置的属性键的列表。如需查看此 slot 继承的服务级属性的键,请使用 PubAdsService.getAttributeKeys
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

slot.getAttributeKeys();
// Returns ['adsense_background_color', 'adsense_border_color'].
返回
string[]属性键数组。顺序未定义。

getCategoryExclusions

getCategoryExclusions(): string[]
返回相应广告位的广告类别排除标签。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

slot.getCategoryExclusions();
// Returns ['AirlineAd', 'TrainAd'].
返回
string[]相应广告位的广告类别排除标签;如果未设置任何标签,则为空数组。

getConfig

getConfig(keys: string | string[]): Pick<SlotSettingsConfig, "adsenseAttributes" | "targeting" | "categoryExclusion">
获取由 setConfig 设置的 slot 的常规配置选项。

并非所有 setConfig() 属性都受此方法支持。支持的属性包括:
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

// Get the value of the `adsenseAttributes` and `categoryExclusion` settings.
const config = slot.getConfig(["adsenseAttributes", "categoryExclusion"]);
参数
keys: string | string[]要获取的配置选项的键。
返回
Pick<SlotSettingsConfig, "adsenseAttributes" | "targeting" | "categoryExclusion">相应 slot 的配置选项。

getResponseInformation

getResponseInformation(): ResponseInformation
返回广告响应信息。此值基于相应广告位的上一次广告响应。如果调用此方法时广告位没有广告,则会返回 null
返回
ResponseInformation最新的广告响应信息,如果相应广告位没有广告,则为 null

getSlotElementId

getSlotElementId(): string
返回定义 slot 时提供的 slot ID div
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

slot.getSlotElementId();
// Returns 'div'.
返回
string位置 div ID。

getTargeting

getTargeting(key: string): string[]
返回在此广告资源位上设置的特定自定义定位参数。不包含服务级定位参数。
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

slot.getTargeting("age");
// Returns [] (empty array).
参数
key: string要查找的定位键。
返回
string[]与此键关联的值;如果没有此类键,则返回一个空数组。

getTargetingKeys

getTargetingKeys(): string[]
返回此广告资源位上设置的所有自定义定位键的列表。不包含服务级定位键。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

slot.getTargetingKeys();
// Returns ['interests', 'allow_expandable'].
返回
string[]定位键数组。顺序未定义。

设置

set(key: string, value: string): Slot
为此广告位上的 AdSense 属性设置一个值。此方法会替换为相应键设置的所有服务级值。

针对同一键多次调用此方法会替换之前为该键设置的值。必须先设置所有值,然后才能调用 displayrefresh
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

// Setting an attribute on a single ad slot.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .set("adsense_background_color", "#FFFFFF")
  .addService(googletag.pubads());
另请参阅
参数
key: string属性的名称。
value: string属性值。
返回
Slot调用方法的 slot 对象。

setCategoryExclusion

setCategoryExclusion(categoryExclusion: string): Slot
为此广告位设置广告位级广告类别排除标签。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

// Label = AirlineAd
googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setCategoryExclusion("AirlineAd")
  .addService(googletag.pubads());
另请参阅
参数
categoryExclusion: string要添加的广告类别排除标签。
返回
Slot调用方法的 slot 对象。

setClickUrl

setClickUrl(value: string): Slot
设置用户点击广告后将被重定向到的点击后到达网址。

即使点击后到达网址被替换,Google Ad Manager 服务器仍会记录点击。与所投放的广告素材相关联的任何着陆页网址都会附加到提供的值中。后续调用会覆盖该值。此方法仅适用于非 SRA 请求。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setClickUrl("http://www.example.com?original_click_url=")
  .addService(googletag.pubads());
参数
value: string要设置的点击后到达网址。
返回
Slot调用方法的 slot 对象。

setCollapseEmptyDiv

setCollapseEmptyDiv(collapse: boolean, collapseBeforeAdFetch?: boolean): Slot
设置在广告位 div 中没有广告时是否应隐藏该广告位。此设置会替换服务级设置。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

googletag
  .defineSlot("/1234567/sports", [160, 600], "div-2")!
  .setCollapseEmptyDiv(true)
  .addService(googletag.pubads());
// The above will cause the div for this slot to be collapsed
// only after GPT detects that no ads are available for the slot.
另请参阅
参数
collapse: boolean是否在未返回任何广告时收缩广告位。
Optional collapseBeforeAdFetch: boolean是否即使在获取广告之前也要合拢广告位。如果 collapse 不为 true,则忽略。
返回
Slot调用方法的 slot 对象。

setConfig

setConfig(slotConfig: SlotSettingsConfig): void
为此 slot 设置常规配置选项。
参数
slotConfig: SlotSettingsConfig配置对象。

setForceSafeFrame

setForceSafeFrame(forceSafeFrame: boolean): Slot
配置相应广告位中的广告是否应强制使用 SafeFrame 容器呈现。

使用此 API 时,请注意以下几点:
  • 此设置仅对相应广告位的后续广告请求生效。
  • 如果指定了广告位级设置,则该设置始终会覆盖网页级设置。
  • 如果设置为 true(在广告位级或网页级),无论在 Google Ad Manager 界面中做出何种选择,广告都将始终使用 SafeFrame 容器呈现。
  • 不过,如果设置为 false 或保持未指定,系统将使用 SafeFrame 容器呈现广告,具体取决于广告素材类型和 Google Ad Manager 界面中的选择。
  • 此 API 应谨慎使用,因为它可能会影响尝试脱离其 iframe 或依赖于直接在发布商网页中呈现的广告素材的行为。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setForceSafeFrame(true)
  .addService(googletag.pubads());
另请参阅
参数
forceSafeFrame: booleantrue 可强制将相应广告位中的所有广告呈现在 SafeFrame 中,而 false 可选择不采用网页级设置(如果有)。如果未在网页级指定此值,将其设置为 false 不会产生任何变化。
返回
Slot调用方法的 slot 对象。

setSafeFrameConfig

setSafeFrameConfig(config: SafeFrameConfig): Slot
为 SafeFrame 配置设置 slot 级偏好设置。系统会忽略配置对象中的所有无法识别的键。如果为识别的键传递了无效值,则整个配置将被忽略。

如果指定了这些广告位级偏好设置,它们将替换任何网页级偏好设置。
示例

JavaScript

googletag.pubads().setForceSafeFrame(true);

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

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

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

JavaScript(旧版)

googletag.pubads().setForceSafeFrame(true);

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

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

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

TypeScript

googletag.pubads().setForceSafeFrame(true);

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

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

googletag.display("div-1");
googletag.display("div-2");
另请参阅
参数
config: SafeFrameConfig配置对象。
返回
Slot调用方法的 slot 对象。

setTargeting

setTargeting(key: string, value: string | string[]): Slot
为此 slot 设置自定义定位参数。针对同一键多次调用此方法会覆盖旧值。此处设置的值将覆盖在服务级设置的定位参数。这些键是在您的 Google Ad Manager 账号中定义的。
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

// Example with multiple values for a key inside in an array.
slot.setTargeting("interests", ["sports", "music"]);
另请参阅
参数
key: string定位参数键。
value: string | string[]定位参数值或值数组。
返回
Slot调用方法的 slot 对象。

updateTargetingFromMap

updateTargetingFromMap(map: {
  [adUnitPath: string]: string | string[];
}): Slot
根据 JSON 对象中的键值对映射,为此广告位设置自定义定位参数。这与针对对象的所有键值调用 Slot.setTargeting 相同。这些键是在您的 Google Ad Manager 账号中定义的。

注意
  • 如果发生覆盖,系统只会保留最后一个值。
  • 如果该值为数组,则任何之前的值都会被覆盖,而不是合并。
  • 此处设置的值将覆盖在服务级设置的定位参数。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

slot.updateTargetingFromMap({
  color: "red",
  interests: ["sports", "music", "movies"],
});
参数
map: {
  [adUnitPath: string]: string | string[];
}
定位参数键值对映射。
返回
Slot调用方法的 slot 对象。

googletag.config

用于页面级设置的主要配置界面。
接口
AdExpansionConfig
用于控制广告展开的设置。
AdSenseAttributesConfig
用于控制 AdSense 广告行为的设置。
ComponentAuctionConfig
一个对象,表示设备端广告竞价中的单个组件竞价。
InterstitialConfig
一个用于定义单个插页式广告广告位的行为的对象。
LazyLoadConfig
用于控制 GPT 中延迟加载的使用情况的设置。
PageSettingsConfig
用于页面级设置的主要配置界面。
PrivacyTreatmentsConfig
用于控制发布商隐私权处理方式的设置。
PublisherProvidedSignalsConfig
发布商提供的信号 (PPS) 配置对象。
SafeFrameConfig
用于控制 GPT 中的 SafeFrame 的设置。
SlotSettingsConfig
用于 slot 级设置的主要配置界面。
TaxonomyData
一个对象,包含单个分类的值。
VideoAdsConfig
用于配置视频广告相关设置的设置。
类型别名
CollapseDivBehavior
用于控制广告位收缩行为的支持值。
InterstitialTrigger
支持的插页式广告触发器。
PrivacyTreatment
支持的发布商隐私保护处理措施。
Taxonomy
发布商提供的信号 (PPS) 支持的分类标准。

类型别名


CollapseDivBehavior

CollapseDivBehavior: "DISABLED" | "BEFORE_FETCH" | "ON_NO_FILL"
用于控制广告位折叠行为的支持值。
另请参阅

InterstitialTrigger

InterstitialTrigger: "unhideWindow" | "navBar"
支持的插页式广告触发器。

PrivacyTreatment

PrivacyTreatment: "disablePersonalization"
支持的发布商隐私保护处理措施。

分类

Taxonomy: "IAB_AUDIENCE_1_1" | "IAB_CONTENT_2_2"
发布商提供的信号 (PPS) 的支持类目。
另请参阅

googletag.config.AdExpansionConfig

用于控制广告展开的设置。
属性
enabled?
广告展开功能是处于启用状态还是停用状态。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

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

属性


Optional 已启用

enabled?: boolean
广告展开功能是启用还是停用。

设置此值会覆盖 Google Ad Manager 中配置的默认值。
另请参阅

googletag.config.AdSenseAttributesConfig

用于控制 AdSense 广告行为的设置。

这些属性可用于按请求替换服务器端设置。
属性
adsense_ad_format?
AdSense 广告格式。
adsense_channel_ids?
AdSense 渠道 ID。
adsense_test_mode?
是否启用了测试模式。
document_language?
展示广告的网页所用的语言。
page_url?
展示广告的网页的网址。
另请参阅

属性


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 广告格式。

Optional adsense_channel_ids

adsense_channel_ids?: string
AdSense 渠道 ID。

允许的值是渠道 ID,以“+”分隔。

示例:271828183+314159265
另请参阅

Optional adsense_test_mode

adsense_test_mode?: "on"
是否启用测试模式。

如果设置为 on,广告会被标记为仅限测试,不会纳入统计或结算范围。对于生产环境中的非测试流量,必须取消设置此属性。

Optional document_language

document_language?: string
展示广告的网页所用的语言。

允许的值是有效的 ISO 639-1 语言代码。

示例:en
另请参阅

Optional page_url

page_url?: string
展示广告的网页的网址。

允许的值是有效的网址。

示例:http://www.example.com

googletag.config.ComponentAuctionConfig

一个对象,表示设备端广告竞价中的单个组件竞价。
属性
auctionConfig
相应组件竞价的竞价配置对象。
configKey
与相应组件竞价相关联的配置键。
另请参阅

属性


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;
}
相应组件竞价的竞价配置对象。

如果此值设置为 null,则会删除指定 configKey 的所有现有配置。
示例

JavaScript

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

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

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

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

JavaScript(旧版)

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

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

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

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

TypeScript

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

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

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

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

configKey

configKey: string
与相应组件竞价相关联的配置键。

此值不得为空,且应是唯一值。如果两个 ComponentAuctionConfig 对象具有相同的 configKey 值,则最后设置的对象会覆盖之前的配置。

googletag.config.InterstitialConfig

一个用于定义单个插页式广告广告位的行为的对象。
属性
requireStorageAccess?
显示此插页式广告是否需要征得用户同意才能使用本地存储空间。
triggers?
相应插页式广告的插页式触发器配置。

属性


Optional requireStorageAccess

requireStorageAccess?: boolean
是否需要用户同意使用本地存储空间才能展示此插页式广告。

GPT 使用本地存储空间来强制控制插页式广告的展示频次上限。不过,即使未同意使用本地存储空间,用户仍有资格看到插页式广告。将此属性设置为 true 可选择停用默认行为,并确保仅向已同意使用本地存储的用户展示插页式广告。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

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

Optional 触发器

triggers?: Partial<Record<InterstitialTrigger, boolean>>
相应插页式广告的插页式触发器配置。

将插页式触发器的值设置为 true 可启用该触发器,设置为 false 可停用该触发器。这会覆盖在 Google Ad Manager 中配置的默认值
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

interstitialSlot.setConfig({
  interstitial: {
    triggers: {
      navBar: enableTriggers,
      unhideWindow: enableTriggers,
    },
  },
});
另请参阅

googletag.config.LazyLoadConfig

用于控制 GPT 中延迟加载的使用情况的设置。
属性
fetchMarginPercent?
在请求广告之前,广告位必须与当前视口的最小距离(以视口大小的百分比表示)。
mobileScaling?
应用于移动设备上边距的乘数。
renderMarginPercent?
在渲染广告之前,广告位必须与当前视口保持的最小距离,以视口大小的百分比表示。
另请参阅

属性


Optional fetchMarginPercent

fetchMarginPercent?: number
在请求广告之前,广告位必须与当前视口的最小距离(以视口大小的百分比表示)。

此设置与 renderMarginPercent 结合使用,可用于预提取广告,但会等待呈现和下载其他子资源。因此,此值应始终大于或等于 renderMarginPercent

值为 0 表示“当广告位进入视口时”,值为 100 表示“当广告距离视口 1 个视口时”,依此类推。

Optional mobileScaling

mobileScaling?: number
应用于移动设备上边距的乘数。此乘数同时应用于 fetchMarginPercentrenderMarginPercent

这样,移动设备和桌面设备上的边距就可以不同,因为它们的视口大小和滚动速度可能不同。例如,如果值为 2.0,则所有边距在移动设备上都会乘以 2,从而增加在提取和渲染之前,广告资源位与视口之间的最小距离。

Optional renderMarginPercent

renderMarginPercent?: number
在渲染广告之前,广告资源位必须与当前视口的最小距离(以视口大小的百分比表示)。

此设置与 fetchMarginPercent 结合使用,可用于预提取广告,但会等待渲染和下载其他子资源。因此,此值应始终小于或等于 fetchMarginPercent

值为 0 表示“当广告位进入视口时”,值为 100 表示“当广告距离视口 1 个视口时”,依此类推。

googletag.config.PageSettingsConfig

用于设置网页级设置的主要配置接口。

允许通过单个 API 调用设置多项功能。

以下列出的所有属性均为示例,并不反映实际使用 setConfig 的功能。如需查看功能集,请参阅下方的 PageSettingsConfig 类型中的字段。

示例:
  • 只有在 googletag.setConfig 调用中指定的功能会被修改。
      // Configure feature alpha.
      googletag.setConfig({
          alpha: {...}
      });
    
      // Configure feature bravo. Feature alpha is unchanged.
      googletag.setConfig({
         bravo: {...}
      });
  • 每次调用 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
          }
      });
  • 通过传递 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,
      });
属性
adExpansion?
用于控制广告展开的设置。
adsenseAttributes?
用于配置 AdSense 属性的设置。
adYield?
已弃用。 
categoryExclusion?
用于配置广告类别排除的设置。
centering?
用于控制广告水平居中的设置。
collapseDiv?
用于控制广告位的收起行为的设置。
disableInitialLoad?
用于控制何时请求广告的设置。
lazyLoad?
用于控制 GPT 中延迟加载的使用情况的设置。
location?
用于将订单项的地理位置定位到特定地理位置的设置。
pps?
用于控制发布商提供的信号 (PPS) 的设置。
privacyTreatments?
用于控制发布商隐私权处理方式的设置。
safeFrame?
用于控制 GPT 中 SafeFrame 使用情况的设置。
singleRequest?
用于启用或停用单一请求架构 (SRA) 的设置。
targeting?
用于控制键值对定位的设置。
threadYield?
用于控制 GPT 在请求和呈现广告素材时是否应让出 JS 线程的设置。
videoAds?
用于控制视频广告的设置。

属性


Optional adExpansion

adExpansion?: AdExpansionConfig
用于控制广告展开的设置。

Optional adsenseAttributes

adsenseAttributes?: AdSenseAttributesConfig
用于配置 AdSense 属性的设置。

通过此设置配置的 AdSense 属性将应用于网页上的所有广告位。此设置可多次调用,以定义多个属性值或覆盖现有值。

AdSense 属性更改仅适用于在此方法调用后请求的广告。因此,建议在调用 googletag.displayPubAdsService.refresh 之前调用此方法。
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

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

Optional adYield

adYield?: "DISABLED" | "ENABLED_ALL_SLOTS"

Optional categoryExclusion

categoryExclusion?: string[]
用于配置广告类别排除的设置。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

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

Optional 居中

centering?: boolean
用于控制广告水平居中的设置。默认情况下,居中处于停用状态。

水平居中更改仅适用于在调用此方法后请求的广告。因此,建议在调用 googletag.displayPubAdsService.refresh 之前调用此方法。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

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

Optional collapseDiv

collapseDiv?: CollapseDivBehavior
用于控制广告位的收起行为的设置。

收起的广告位不会占用网页上的任何空间。

支持的值:
  • null(默认值):相应广告资源不会折叠。
  • DISABLED:无论是否返回广告,广告位都不会收缩。
  • BEFORE_FETCH:广告位最初处于收起状态,当返回广告时会展开。
  • ON_NO_FILL:广告位一开始会处于展开状态,如果没有返回广告,则会收起。
示例

JavaScript

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

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

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

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

JavaScript(旧版)

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

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

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

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

TypeScript

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

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

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

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

Optional disableInitialLoad

disableInitialLoad?: boolean
用于控制何时请求广告的设置。

默认情况下,googletag.display 方法既会注册广告位,也会为这些广告位请求广告。不过,有时最好将这些操作分开,以便更精确地控制广告内容的加载时间。

启用此设置后,当调用 display() 方法时,系统不会为已注册的 slot 请求广告。您必须单独调用 PubAdsService.refresh 才能发起广告请求。

此方法必须在调用 googletag.enableServices 之前调用。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

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

Optional lazyLoad

lazyLoad?: LazyLoadConfig
用于控制在 GPT 中使用延迟加载的设置。

延迟加载是一种技术,可延迟广告的请求和呈现,直到广告接近用户的视口时才进行。如需更详细的示例,请参阅延迟加载示例。

注意:如果启用了 singleRequest,则只有当所有广告资源位都位于提取边距之外时,延迟提取才会生效。

在调用 setConfig() 时未指定的任何延迟加载设置都将使用 Google 设置的默认值。这些默认值可能会随着时间的推移而调整。如需停用特定设置,请将值设置为 null
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

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

Optional location

location?: string
用于将订单项的地理位置定位条件设置为地理位置的设置。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

// Clear the location setting.
googletag.setConfig({ location: null });
另请参阅

Optional pps

用于控制发布商提供的信号 (PPS) 的设置。

Optional privacyTreatments

privacyTreatments?: PrivacyTreatmentsConfig
用于控制发布商隐私权处理方式的设置。

Optional safeFrame

safeFrame?: SafeFrameConfig
用于控制 GPT 中 SafeFrame 的使用情况的设置。

通过此设置配置的值将应用于网页上的所有广告位。各个广告位可以通过 SlotSettingsConfig.safeFrame 替换这些值。
示例

JavaScript

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

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

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

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

JavaScript(旧版)

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

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

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

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

TypeScript

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

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

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

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

Optional singleRequest

singleRequest?: boolean
用于启用或停用单一请求架构 (SRA) 的设置。

启用 SRA 后,在 googletag.displayPubAdsService.refresh 调用之前定义的所有广告位都将批量处理到单个广告请求中。这不仅有助于提高效果,也是确保包版广告和竞争性排除规则能够正常发挥作用的必要条件。

如果停用 SRA,系统会单独请求每个广告位。这是 GPT 的默认行为。

此方法必须在调用 googletag.enableServices 之前调用。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

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

Optional 定位

targeting?: Record<string, string | string[]>
用于控制键值对定位的设置。

通过此设置配置的定位条件将应用于网页上的所有广告位。此设置可多次调用,以定义多个定位键值对或覆盖现有值。定位键是在您的 Google Ad Manager 账号中定义的。
示例

JavaScript

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

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

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

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

JavaScript(旧版)

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

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

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

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

TypeScript

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

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

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

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

Optional threadYield

threadYield?: "DISABLED" | "ENABLED_ALL_SLOTS"
用于控制 GPT 在请求和呈现广告素材时是否应让出 JS 线程的设置。

GPT 仅会针对支持 Scheduler.postTask 或 Scheduler.yield API 的浏览器让出线程。

支持的值:
  • null(默认):对于视口外的广告位,GPT 将让出 JS 线程。
  • ENABLED_ALL_SLOTS:无论广告位是否位于视口内,GPT 都会为所有广告位让出 JS 线程。
  • DISABLED:GPT 不会产生 JS 线程。
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

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

Optional videoAds

videoAds?: VideoAdsConfig
用于控制视频广告的设置。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

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

googletag.config.PrivacyTreatmentsConfig

用于控制发布商隐私权处理方式的设置。
属性
treatments
要启用的发布商隐私保护处理措施的数组。

属性


处理

treatments: "disablePersonalization"[]
要启用的一系列发布商隐私保护处理措施。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

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

googletag.config.PublisherProvidedSignalsConfig

发布商提供的信号 (PPS) 配置对象。
属性
taxonomies
一个包含 Taxonomy 映射的对象,或用于清除配置的 null。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

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

属性


分类

taxonomies: Partial<Record<Taxonomy, TaxonomyData>>
一个包含 Taxonomy 映射的对象,或用于清除配置的 null。

googletag.config.SafeFrameConfig

用于控制 GPT 中的 SafeFrame 的设置。
属性
allowOverlayExpansion?
SafeFrame 是否应允许广告内容通过叠加网页内容进行展开。
allowPushExpansion?
SafeFrame 是否应允许广告内容通过推送网页内容来展开。
forceSafeFrame?
是否应强制使用 SafeFrame 容器呈现广告。
sandbox?
SafeFrame 是否应使用 HTML5 沙盒属性来阻止在没有用户互动的情况下进行顶层导航。
useUniqueDomain?
已弃用。 SafeFrame 是否应为预订型广告素材使用随机子网域。
另请参阅

属性


Optional allowOverlayExpansion

allowOverlayExpansion?: boolean
SafeFrame 是否应允许广告内容通过叠加网页内容进行展开。

Optional allowPushExpansion

allowPushExpansion?: boolean
SafeFrame 是否应允许广告内容通过推送网页内容来展开。

Optional forceSafeFrame

forceSafeFrame?: boolean
是否应强制使用 SafeFrame 容器呈现广告。

Optional 沙盒

sandbox?: boolean
SafeFrame 是否应使用 HTML5 沙盒属性来阻止在没有用户互动的情况下进行顶层导航。唯一有效值为 true(无法强制设为 false)。请注意,sandbox 属性会停用插件(例如 Flash)。

Optional useUniqueDomain

useUniqueDomain?: boolean
SafeFrame 是否应为预订型广告素材使用随机子网域。传入 null 可清除存储的值。

注意:此功能默认处于启用状态。
另请参阅

googletag.config.SlotSettingsConfig

用于设置 slot 级设置的主要配置接口。

允许通过单个 API 调用为单个 slot 设置多项功能。

以下列出的所有属性均为示例,并不反映实际使用 setConfig 的功能。如需了解功能集,请参阅下方的 SlotSettingsConfig 类型中的字段。

示例:
  • 仅修改 Slot.setConfig 调用中指定的功能。
      const slot = googletag.defineSlot("/1234567/example", [160, 600]);
    
      // Configure feature alpha.
      slot.setConfig({
          alpha: {...}
      });
    
      // Configure feature bravo. Feature alpha is unchanged.
      slot.setConfig({
         bravo: {...}
      });
  • 每次调用 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
          }
      });
  • 通过传递 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,
      });
属性
adExpansion?
用于配置广告扩展功能的设置。
adsenseAttributes?
用于配置 AdSense 属性的设置。
categoryExclusion?
用于配置广告类别排除的设置。
clickUrl?
用于配置用户点击广告后将被重定向到的网址的设置。
collapseDiv?
用于配置广告展示位置收缩行为的设置。
componentAuction?
要纳入设备端广告竞价中的组件竞价数组。
interstitial?
用于配置插页式广告广告资源位行为的设置。
safeFrame?
用于配置 GPT 中 SafeFrame 使用情况的设置。
targeting?
用于配置键值对定位的设置。

属性


Optional adExpansion

adExpansion?: AdExpansionConfig
用于配置广告扩展功能的设置。
另请参阅

Optional adsenseAttributes

adsenseAttributes?: AdSenseAttributesConfig
用于配置 AdSense 属性的设置。

通过此设置配置的 AdSense 属性仅适用于相应广告展示位置。此设置可多次调用,以定义多个属性值或覆盖现有值。

AdSense 属性更改仅适用于在此方法调用后请求的广告。因此,建议在调用 googletag.displayPubAdsService.refresh 之前调用此方法。
示例

JavaScript

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

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

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

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

JavaScript(旧版)

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

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

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

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

TypeScript

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

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

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

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

Optional categoryExclusion

categoryExclusion?: string[]
用于配置广告类别排除的设置。
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

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

Optional clickUrl

clickUrl?: string
用于配置用户点击广告后会被重定向到的网址的设置。

即使点击网址被替换,Google Ad Manager 服务器仍会记录点击。与所投放的广告素材相关联的任何着陆页网址都会附加到提供的值中。多次设置此值会覆盖之前配置的所有值。传入 null 会清除该值。

注意:此设置仅适用于非 SRA 请求
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

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

Optional collapseDiv

collapseDiv?: CollapseDivBehavior
用于配置广告位的收起行为的设置。

收起的广告位不会占用网页上的任何空间。

支持的值:
  • null(默认值):相应广告资源不会折叠。
  • DISABLED:无论是否返回广告,广告位都不会收缩。
  • BEFORE_FETCH:广告位最初处于收起状态,当返回广告时会展开。
  • ON_NO_FILL:广告位一开始会处于展开状态,如果没有返回广告,则会收起。
示例

JavaScript

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

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

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

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

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

JavaScript(旧版)

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

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

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

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

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

TypeScript

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

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

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

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

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

Optional componentAuction

componentAuction?: ComponentAuctionConfig[]
要纳入设备端广告竞价中的组件竞价数组。

Optional 插页式广告

interstitial?: InterstitialConfig
用于配置插页式广告展示位置行为的设置。
另请参阅

Optional safeFrame

safeFrame?: SafeFrameConfig
用于在 GPT 中配置 SafeFrame 使用情况的设置。

通过此设置配置的值仅适用于相应广告位,并会覆盖通过 PageSettingsConfig.safeFrame 设置的值。
示例

JavaScript

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

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

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

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

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

JavaScript(旧版)

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

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

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

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

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

TypeScript

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

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

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

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

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

Optional 定位

targeting?: Record<string, string | string[]>
用于配置键值对定位条件的设置。

通过此设置配置的定位条件仅适用于相应广告位。此设置可多次调用,以定义多个定位键值对或覆盖现有值。定位键是在您的 Google Ad Manager 账号中定义的。
示例

JavaScript

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

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

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

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

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

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

JavaScript(旧版)

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

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

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

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

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

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

TypeScript

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

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

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

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

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

// Clear all targeting keys.
slot.setConfig({ targeting: null });
另请参阅

googletag.config.TaxonomyData

一个对象,包含单个分类的值。
属性
values
分类值的列表。

属性


values: readonly string[]
分类值的列表。

googletag.config.VideoAdsConfig

用于配置视频广告相关设置的设置。
属性
enableVideoAds
网页上是否会显示视频广告。
videoCmsId?
视频内容来源 ID。
videoContentId?
视频内容 ID。
另请参阅

属性


enableVideoAds

enableVideoAds: boolean
网页上是否会展示视频广告。

如果设置为 true,则会对展示广告和视频广告启用内容排除限制。

如果视频内容已知,请将 videoContentIdvideoCmsId 设置为提供给 Google Ad Manager 内容提取服务的值,以便对展示广告使用内容排除功能。

Optional videoCmsId

videoCmsId?: string
视频内容来源 ID。

这是由 Google Ad Manager 内容提取服务分配的唯一值,用于标识由 videoContentId 指定的视频内容的来源。
另请参阅

Optional videoContentId

videoContentId?: string
视频内容 ID。

这是一个唯一值,用于标识由 videoCmsId 指定的内容来源中的特定视频。此值由托管视频内容的 CMS 分配。
另请参阅

googletag.enums

这是 GPT 用于枚举类型的命名空间。
枚举
OutOfPageFormat
GPT 支持的页外广告格式。
TrafficSource
GPT 支持的流量来源

枚举


OutOfPageFormat

OutOfPageFormat
GPT 支持的页外广告格式。
另请参阅
枚举成员
AD_INTENTS
广告意向格式。
BOTTOM_ANCHOR
广告位固定在视口底部的锚定广告格式。
GAME_MANUAL_INTERSTITIAL
游戏手册插页式广告格式。

注意:游戏手册插页式广告是一种访问受限的格式。
INTERSTITIAL
网页插页式广告素材格式。
LEFT_SIDE_RAIL
左侧边栏广告格式。
REWARDED
激励广告格式。
RIGHT_SIDE_RAIL
右侧边栏广告格式。
TOP_ANCHOR
广告位固定在视口顶部的锚定广告格式。

TrafficSource

TrafficSource
GPT 支持的流量来源
另请参阅
枚举成员
ORGANIC
直接网址输入、网站搜索或应用下载。
PURCHASED
从非自有媒体资源重定向的流量(已收购或其他利诱性质的活动)。

googletag.events

这是 GPT 用于事件的命名空间。您的代码可以使用 Service.addEventListener 对这些事件做出反应。
接口
Event
所有 GPT 事件的基本接口。
EventTypeMap
这是一个伪类型,用于将事件名称映射到 Service.addEventListenerService.removeEventListener 的相应事件对象类型。
GameManualInterstitialSlotClosedEvent
当用户关闭游戏手册插页式广告展示位置时,系统会触发此事件。
GameManualInterstitialSlotReadyEvent
当游戏手册插页式广告位可以向用户展示时,系统会触发此事件。
ImpressionViewableEvent
当展示符合 Active View 标准而变为可见时,系统会触发此事件。
RewardedSlotClosedEvent
当用户关闭激励广告展示位置时,系统会触发此事件。
RewardedSlotGrantedEvent
用户因观看激励广告而获得奖励时,系统会触发此事件。
RewardedSlotReadyEvent
激励广告准备好展示时,系统会触发此事件。
RewardedSlotVideoCompletedEvent
此事件会在激励视频广告播放完毕时触发。
SlotOnloadEvent
当广告素材的 iframe 触发其加载事件时,系统会触发此事件。
SlotRenderEndedEvent
此事件在广告素材代码注入到展示位置时触发。
SlotRequestedEvent
当已为特定 slot 请求广告时,系统会触发此事件。
SlotResponseReceived
当特定广告位的广告响应已收到时,会触发此事件。
SlotVisibilityChangedEvent
每当广告资源块区域的屏幕显示百分比发生变化时,就会触发此事件。

googletag.events.Event

所有 GPT 事件的基本接口。以下所有 GPT 事件都将包含以下字段。
属性
serviceName
触发事件的服务的名称。
slot
触发事件的 slot。
另请参阅

属性


serviceName

serviceName: string
触发事件的服务的名称。

slot

slot: Slot
触发事件的 slot。

googletag.events.EventTypeMap

这是一种伪类型,用于将事件名称映射到 Service.addEventListenerService.removeEventListener 的相应事件对象类型。记录此属性仅用于参考和类型安全目的。
属性
gameManualInterstitialSlotClosed
gameManualInterstitialSlotReady
impressionViewable
rewardedSlotClosed
rewardedSlotGranted
rewardedSlotReady
rewardedSlotVideoCompleted
slotOnload
slotRenderEnded
slotRequested
slotResponseReceived
slotVisibilityChanged

属性


gameManualInterstitialSlotClosed


gameManualInterstitialSlotReady


impressionViewable


rewardedSlotClosed


rewardedSlotGranted


rewardedSlotReady


rewardedSlotVideoCompleted


slotOnload

slotOnload: SlotOnloadEvent
events.SlotOnloadEvent 的别名。

slotRenderEnded


slotRequested


slotResponseReceived

slotResponseReceived: SlotResponseReceived
events.SlotResponseReceived 的别名。

slotVisibilityChanged


googletag.events.GameManualInterstitialSlotClosedEvent

扩展 Event
当用户关闭游戏手册插页式广告位时,系统会触发此事件。

注意:游戏手册插页式广告是一种访问受限的格式。
属性
serviceName
触发事件的服务的名称。
slot
触发事件的 slot。
示例

JavaScript

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

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

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

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

JavaScript(旧版)

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

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

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

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

TypeScript

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

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

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

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
另请参阅

googletag.events.GameManualInterstitialSlotReadyEvent

扩展 Event
当游戏手动插页式广告位已可以向用户展示时,系统会触发此事件。

注意:游戏手动插页式广告是一种访问受限的格式。
属性
serviceName
触发事件的服务的名称。
slot
触发事件的 slot。
方法
makeGameManualInterstitialVisible
向用户展示游戏手册插页式广告。
示例

JavaScript

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

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

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

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

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

JavaScript(旧版)

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

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

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

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

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

TypeScript

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

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

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

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

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
另请参阅

方法


makeGameManualInterstitialVisible

makeGameManualInterstitialVisible(): void
向用户展示游戏手册插页式广告。

googletag.events.ImpressionViewableEvent

扩展 Event
当展示符合 Active View 标准而变为可见时,系统会触发此事件。
属性
serviceName
触发事件的服务的名称。
slot
触发事件的 slot。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
另请参阅

googletag.events.RewardedSlotClosedEvent

扩展 Event
当用户关闭激励广告展示位置时,系统会触发此事件。它可以在授予奖励之前或之后触发。如需确定是否已授予奖励,请改用 events.RewardedSlotGrantedEvent
属性
serviceName
触发事件的服务的名称。
slot
触发事件的 slot。
示例

JavaScript

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

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

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

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

JavaScript(旧版)

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

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

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

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

TypeScript

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

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

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

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
另请参阅

googletag.events.RewardedSlotGrantedEvent

扩展 Event
用户因观看激励广告而获得奖励时,系统会触发此事件。如果广告在满足奖励授予条件之前关闭,则不会触发此事件。
属性
payload
一个包含已授予奖励相关信息的对象。
serviceName
触发事件的服务的名称。
slot
触发事件的 slot。
示例

JavaScript

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

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

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

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

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

JavaScript(旧版)

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

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

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

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

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

TypeScript

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

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

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

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

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
另请参阅

属性


载荷

一个包含已授予奖励相关信息的对象。

googletag.events.RewardedSlotReadyEvent

扩展 Event
激励广告准备好展示时,系统会触发此事件。发布商负责在展示广告之前向用户提供观看广告的选项。
属性
serviceName
触发事件的服务的名称。
slot
触发事件的 slot。
方法
makeRewardedVisible
显示激励广告。
示例

JavaScript

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

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

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

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

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

JavaScript(旧版)

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

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

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

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

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

TypeScript

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

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

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

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

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
另请参阅

方法


makeRewardedVisible

makeRewardedVisible(): void
显示激励广告。在用户同意观看广告之前,不应调用此方法。

googletag.events.RewardedSlotVideoCompletedEvent

扩展 Event
此事件会在激励视频广告播放完毕时触发。
属性
serviceName
触发事件的服务的名称。
slot
触发事件的 slot。
示例

JavaScript

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

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

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

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

JavaScript(旧版)

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

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

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

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

TypeScript

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

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

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

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
另请参阅

googletag.events.SlotOnloadEvent

扩展 Event
当广告素材的 iframe 触发其加载事件时,系统会触发此事件。在同步呈现模式下呈现富媒体广告时,不会使用 iframe,因此不会触发 SlotOnloadEvent
属性
serviceName
触发事件的服务的名称。
slot
触发事件的 slot。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
另请参阅

googletag.events.SlotRenderEndedEvent

扩展 Event
当广告素材代码注入到广告资源时,系统会触发此事件。此事件将在提取广告素材资源之前发生,因此广告素材可能尚未显示。如果您需要了解某个广告位的全部广告素材资源何时加载完毕,请考虑使用 events.SlotOnloadEvent
属性
advertiserId
已呈现广告的广告客户 ID。
campaignId
已呈现广告的广告系列 ID。
companyIds
对呈现的补余广告出价的公司的 ID。
creativeId
已呈现的预留广告的广告素材 ID。
creativeTemplateId
已呈现的预留广告的广告素材模板 ID。
isBackfill
广告是否为补余广告。
isEmpty
相应广告位是否返回了广告。
labelIds
已弃用。 
lineItemId
已呈现的预留广告的订单项 ID。
responseIdentifier
响应标识符是广告响应的唯一标识符。
serviceName
触发事件的服务的名称。
size
表示已渲染广告素材的像素尺寸。
slot
触发事件的 slot。
slotContentChanged
插槽内容是否随呈现的广告而更改。
sourceAgnosticCreativeId
已呈现的预订广告或补余广告的广告素材 ID。
sourceAgnosticLineItemId
已呈现的预订广告或补余广告的订单项 ID。
yieldGroupIds
已呈现的填充广告的收益组 ID。
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
另请参阅

属性


advertiserId

advertiserId: number
已呈现广告的广告客户 ID。对于空广告位、填充广告以及由 PubAdsService 以外的服务呈现的广告素材,此值为 null

campaignId

campaignId: number
已呈现广告的广告系列 ID。对于空广告位、填充广告以及由 PubAdsService 以外的服务呈现的广告素材,此值为 null

companyIds

companyIds: number[]
对呈现的补余广告出价的公司的 ID。对于空槽、预留广告和由 PubAdsService 以外的服务呈现的广告素材,此值为 null

creativeId

creativeId: number
已呈现的预留广告的广告素材 ID。对于空广告位、填充广告以及由 PubAdsService 以外的服务呈现的广告素材,此值为 null

creativeTemplateId

creativeTemplateId: number
已呈现的预留广告的广告素材模板 ID。对于空广告位、填充广告以及由 PubAdsService 以外的服务呈现的广告素材,此值为 null

isBackfill

isBackfill: boolean
广告是否为补余广告。如果广告是补余广告,则值为 true;否则值为 false

isEmpty

isEmpty: boolean
相应广告位是否返回了广告。如果没有返回任何广告,则值为 true;否则为 false

labelIds

labelIds: number[]

lineItemId

lineItemId: number
已呈现的预留广告的订单项 ID。对于空广告位、填充广告以及由 PubAdsService 以外的服务呈现的广告素材,此值为 null

responseIdentifier

responseIdentifier: string
响应标识符是广告响应的唯一标识符。此值可用于在广告查看中心 (ARC) 中识别和屏蔽广告。

size

size: string | number[]
表示已呈现的广告素材的像素大小。示例:[728, 90]。对于空白广告位,该值为 null

slotContentChanged

slotContentChanged: boolean
插槽内容是否随呈现的广告而发生变化。如果内容已更改,则值为 true;否则值为 false

sourceAgnosticCreativeId

sourceAgnosticCreativeId: number
已呈现的预留广告或补余广告的广告素材 ID。如果广告不是预订型广告或订单项填充广告,或者广告素材由 PubAdsService 以外的服务呈现,则值为 null

sourceAgnosticLineItemId

sourceAgnosticLineItemId: number
已呈现的预订广告或补余广告的订单项 ID。如果广告不是预订型广告或订单项填充广告,或者广告素材由 PubAdsService 以外的服务呈现,则值为 null

yieldGroupIds

yieldGroupIds: number[]
已呈现的填充广告的收益组 ID。对于空槽、预留广告和由 PubAdsService 以外的服务呈现的广告素材,此值为 null

googletag.events.SlotRequestedEvent

扩展 Event
当已为特定 slot 请求广告时,系统会触发此事件。
属性
serviceName
触发事件的服务的名称。
slot
触发事件的 slot。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
另请参阅

googletag.events.SlotResponseReceived

扩展 Event
当特定广告位的广告响应已收到时,会触发此事件。
属性
serviceName
触发事件的服务的名称。
slot
触发事件的 slot。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
另请参阅

googletag.events.SlotVisibilityChangedEvent

扩展 Event
每当广告资源块区域的屏幕显示百分比发生变化时,就会触发此事件。该事件会受到限制,触发频率不会超过每 200 毫秒一次。
属性
inViewPercentage
广告的可见面积所占的百分比。
serviceName
触发事件的服务的名称。
slot
触发事件的 slot。
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
另请参阅

属性


inViewPercentage

inViewPercentage: number
广告的可见面积所占的百分比。值是介于 0 到 100 之间的数字。

googletag.secureSignals

这是 GPT 用于管理安全信号的命名空间。
接口
BidderSignalProvider
返回特定出价方的安全信号。
PublisherSignalProvider
返回特定发布商的安全信号。
SecureSignalProvidersArray
用于管理安全信号的接口。
类型别名
SecureSignalProvider
用于为特定出价方或提供方返回安全信号的接口。

类型别名


SecureSignalProvider

用于针对特定出价方或提供方返回安全信号的接口。必须提供 idnetworkCode 中的一个,但不能同时提供这两者。

googletag.secureSignals.BidderSignalProvider

针对特定出价方返回安全信号。

出价方安全信号提供程序包含 2 个部分:

  1. 一个收集器函数,返回一个解析为安全信号的 Promise
  2. 一个 id,用于标识与信号关联的出价方。
如需为发布商返回安全信号,请改用 secureSignals.PublisherSignalProvider
属性
collectorFunction
一种函数,可返回解析为安全信号的 Promise
id
与此安全信号关联的收集器的唯一标识符,如在 Google Ad Manager 中注册的一样。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

// id is provided
googletag.secureSignalProviders!.push({
  id: "collector123",
  collectorFunction: () => {
    // ...custom signal generation logic...
    return Promise.resolve("signal");
  },
});
另请参阅

属性


collectorFunction

collectorFunction: (() => Promise<string>)
一种函数,可返回解析为安全信号的 Promise

id

id: string
与此安全信号关联的收集器的唯一标识符,如在 Google Ad Manager 中注册的一样。

googletag.secureSignals.PublisherSignalProvider

返回特定发布商的安全信号。

发布商信号提供方由两部分组成:

  1. 一个收集器函数,返回一个解析为安全信号的 Promise
  2. 用于标识与信号相关联的发布商的 networkCode
如需为出价方返回安全信号,请改用 secureSignals.BidderSignalProvider
属性
collectorFunction
一种函数,可返回解析为安全信号的 Promise
networkCode
与此安全信号相关联的发布商的广告资源网代码(如广告资源网路径中所示)。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

// networkCode is provided
googletag.secureSignalProviders!.push({
  networkCode: "123456",
  collectorFunction: () => {
    // ...custom signal generation logic...
    return Promise.resolve("signal");
  },
});
另请参阅

属性


collectorFunction

collectorFunction: (() => Promise<string>)
一种函数,可返回解析为安全信号的 Promise

networkCode

networkCode: string
与此安全信号相关联的发布商的广告资源网代码(如广告资源网路径中所示)。

googletag.secureSignals.SecureSignalProvidersArray

用于管理安全信号的接口。
方法
clearAllCache
从缓存中清除所有收集器的所有信号。
push
向信号提供程序数组添加新的 secureSignals.SecureSignalProvider,并开始信号生成过程。

方法


clearAllCache

clearAllCache(): void
清除缓存中所有收集器的所有信号。

调用此方法可能会降低在当前和潜在的后续网页浏览中,信号被纳入广告请求的可能性。因此,只有在发生有意义的状态更改(例如,发生表明有新用户的事件,如登录、注销、注册等)时,才应调用此方法。

推送

push(provider: SecureSignalProvider): void
向信号提供程序数组添加新的 secureSignals.SecureSignalProvider,并开始信号生成过程。
参数
provider: SecureSignalProvider要添加到数组中的 secureSignals.SecureSignalProvider 对象。