GPT 参考文档

此参考文档使用 TypeScript 表示法来描述类型。下表通过示例进行了简要说明。

类型表达式
string 原初字符串类型。
string[] 数组类型,其中值只能是字符串。
number | string 联合类型,其值可以是数字或字符串。
Array<number | string> 数组类型,其中值为复杂(联合)类型。
[number, string] 元组类型,其值是一个双元素数组,必须按顺序包含一个数字和一个字符串。
Slot 对象类型,其中值为 googletag.Slot 的实例。
() => void 没有定义实参且没有返回值的函数类型。

如需详细了解支持的类型和类型表达式,请参阅 TypeScript 手册 。

类型注解

变量、形参名称、属性名称或函数签名后面的冒号表示类型注解。类型注解描述了冒号左侧的元素可以接受或返回的类型。下表显示了您可能会在此参考文档中看到的类型注解示例。

类型注解
param: string 表示 param 接受或返回字符串值。此语法用于变量、形参、属性和返回值类型。
param?: number | string 表示 param 是可选的,但在指定时接受数字或字符串。此语法用于参数和属性。
...params: Array<() => void> 表示 params 是一个接受函数的 剩余形参 。Rest 参数接受指定类型的无限数量的值。

googletag

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

类型别名


FluidSize

FluidSize: "fluid"
尺寸字符串,其中广告容器占据其父级 div 的 100% 宽度,然后调整其高度以适应广告素材内容。这与网页上常规块元素的行为类似。用于原生广告和横幅广告(请参阅相关文章)。

GeneralSize

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

MultiSize

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

NamedSize

NamedSize: FluidSize | [FluidSize]
广告位可以具有的命名尺寸。在大多数情况下,尺寸是固定大小的矩形,但在某些情况下,我们需要其他类型的尺寸规范。只有以下是有效的具名尺寸:
  • 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 已启用、已加载且可完全正常运行。在调用 enableServices 且 PubAdsService 加载并初始化之前,此属性将只是 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新创建的槽位;如果无法创建槽位,则为 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新创建的槽位;如果无法创建槽位,则为 null。

destroySlots

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

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

具体而言,销毁广告位会从 GPT 的长效网页浏览中移除广告,因此未来的请求不会受到涉及此广告的包版或竞争性排除的影响。如果在从页面中移除广告位的 div 之前未能调用此函数,将会导致未定义的行为。
示例

JavaScript

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

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

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

// This call to destroy all slots.
googletag.destroySlots();

JavaScript(旧版)

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

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

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

// This call to destroy all slots.
googletag.destroySlots();

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

display(divOrSlot: string | Element | Slot): void
指示槽位服务呈现槽位。每个广告位在每个网页上只能展示一次。所有时段都必须先进行定义并关联服务,然后才能显示。只有在元素存在于 DOM 中时,才能发出显示调用。通常,您可以在方法调用中命名的 div 元素内的脚本块中放置该方法。

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

enableServices

enableServices(): void
启用已为网页上的广告位定义的所有 GPT 服务。

getConfig

getConfig(keys: string | string[]): Readonly<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[]要获取的配置选项的键。
返回
Readonly<Pick<PageSettingsConfig, "adsenseAttributes" | "disableInitialLoad" | "targeting">>页面配置选项的冻结副本。

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

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
获取与此服务关联的时段列表。
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?
使广告投放能够在受限数据处理模式下运行,以帮助发布商满足监管合规需求。
tagForAgeTreatment?
年龄限制处理方式,用于指明广告请求是否应被视为面向儿童、青少年或年龄不明的用户。
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 tagForAgeTreatment

tagForAgeTreatment?: TagForAgeTreatment
年龄限制处理方式,用于指明广告请求是否应被视为面向儿童、青少年或年龄不明的用户。

请咨询您的法律顾问,依据自身法律及监管要求,为用户确定年龄处理方式设置。如需详细了解此设置,请参阅这篇帮助中心文章。

设置此属性即表示您保证此通知准确无误,并且您有权代表网站所有者行事。您了解,滥用此设置可能会导致您的 Google 账号被终止。
示例

JavaScript

// Enable teen privacy treatment.
googletag.pubads().setPrivacySettings({
  tagForAgeTreatment: googletag.enums.TagForAgeTreatment.TEEN,
});

// Clear age treatment configuration.
googletag.pubads().setPrivacySettings({
  tagForAgeTreatment: googletag.enums.TagForAgeTreatment.UNSPECIFIED,
});

JavaScript(旧版)

// Enable teen privacy treatment.
googletag.pubads().setPrivacySettings({
  tagForAgeTreatment: googletag.enums.TagForAgeTreatment.TEEN,
});

// Clear age treatment configuration.
googletag.pubads().setPrivacySettings({
  tagForAgeTreatment: googletag.enums.TagForAgeTreatment.UNSPECIFIED,
});

TypeScript

// Enable teen privacy treatment.
googletag.pubads().setPrivacySettings({
  tagForAgeTreatment: googletag.enums.TagForAgeTreatment.TEEN,
});

// Clear age treatment configuration.
googletag.pubads().setPrivacySettings({
  tagForAgeTreatment: googletag.enums.TagForAgeTreatment.UNSPECIFIED,
});

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

方法


clear

clear(slots?: Slot[]): boolean
从给定广告位中移除广告,并将其替换为空白内容。这些广告位将被标记为未提取。

具体而言,清空广告位会从 GPT 的长效网页浏览中移除广告,因此未来的请求不会受到涉及此广告的包版或竞争性排除的影响。
示例

JavaScript

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

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

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

// This call to clear all slots.
googletag.pubads().clear();

JavaScript(旧版)

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

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

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

// This call to clear all slots.
googletag.pubads().clear();

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[]要清除的槽位数组。数组是可选的;如果未指定,则所有槽都将被清除。
返回
boolean如果槽位已清除,则返回 true,否则返回 false。

clearCategoryExclusions

clearCategoryExclusions(): PubAdsService
清除所有网页级广告类别排除标签。如果您想刷新广告位,此方法会很有用。
示例

JavaScript

// Set category exclusion to exclude ads with 'AirlineAd' labels.
googletag.setConfig({
  categoryExclusion: ["AirlineAd"],
});

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

// Clear category exclusions so all ads can be returned.
googletag.setConfig({
  categoryExclusion: null,
});

// Make ad requests. Any ad can be returned.

JavaScript(旧版)

// Set category exclusion to exclude ads with 'AirlineAd' labels.
googletag.setConfig({
  categoryExclusion: ["AirlineAd"],
});

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

// Clear category exclusions so all ads can be returned.
googletag.setConfig({
  categoryExclusion: null,
});

// Make ad requests. Any ad can be returned.

TypeScript

// Set category exclusion to exclude ads with 'AirlineAd' labels.
googletag.setConfig({
  categoryExclusion: ["AirlineAd"],
});

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

// Clear category exclusions so all ads can be returned.
googletag.setConfig({
  categoryExclusion: null,
});

// Make ad requests. Any ad can be returned.
另请参阅
返回
PubAdsService调用该方法的服务对象。

clearTargeting

clearTargeting(key?: string): PubAdsService
清除特定键或所有键的自定义定位参数。
示例

JavaScript

googletag.setConfig({
  targeting: {
    interests: "sports",
    colors: "blue",
    fruits: "apple",
  },
});

googletag.setConfig({
  targeting: {
    interests: null,
  },
});
// Targeting 'colors' and 'fruits' are still present, while 'interests'
// was cleared.

googletag.setConfig({
  targeting: null,
});
// All targeting has been cleared.

JavaScript(旧版)

googletag.setConfig({
  targeting: {
    interests: "sports",
    colors: "blue",
    fruits: "apple",
  },
});

googletag.setConfig({
  targeting: {
    interests: null,
  },
});
// Targeting 'colors' and 'fruits' are still present, while 'interests'
// was cleared.

googletag.setConfig({
  targeting: null,
});
// All targeting has been cleared.

TypeScript

googletag.setConfig({
  targeting: {
    interests: "sports",
    colors: "blue",
    fruits: "apple",
  },
});

googletag.setConfig({
  targeting: {
    interests: null,
  },
});
// Targeting 'colors' and 'fruits' are still present, while 'interests'
// was cleared.

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

collapseEmptyDivs

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

disableInitialLoad

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

display

display(adUnitPath: string, size: GeneralSize, div?: string | Element, clickUrl?: string): void
使用给定的广告单元路径和尺寸构建并展示广告位。

此方法是先调用 googletag.defineSlot,然后立即调用 googletag.display 的简写形式。

此方法的行为取决于是否启用了单一请求架构 (SRA):
  • 已启用 SRA:截至此次调用时定义的所有广告位都将进行批处理并一起请求。
  • SRA 已停用(默认):广告位将单独请求。
注意:调用此方法时,系统会创建广告位和网页状态的快照,以确保在发送广告请求和呈现响应时保持一致。调用此方法后对广告位或网页状态所做的任何更改(包括定位、隐私设置、强制使用 SafeFrame 等)都只会应用于后续的 display() 或 refresh() 请求。
示例

JavaScript

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

JavaScript(旧版)

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

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 中启用延迟加载(由配置对象定义)。如需查看更详细的示例,请参阅延迟加载示例。

注意:只有当所有广告位都位于提取边距之外时,SRA 中的延迟提取才会起作用。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

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,
  },
});
另请参阅
参数
Optional config: {
  fetchMarginPercent?: number;
  mobileScaling?: number;
  renderMarginPercent?: number;
}
配置对象允许自定义延迟行为。任何省略的配置都将使用 Google 设置的默认值,这些默认值会随着时间的推移而调整。如需停用特定设置(例如提取边距),请将值设置为 -1。
  • fetchMarginPercent

    广告位与当前视口之间的最小距离(以视口大小的百分比表示),达到此距离后我们才会提取广告。值为 0 表示“当广告位进入视口时”,值为 100 表示“当广告距离视口 1 个视口高度时”,以此类推。
  • renderMarginPercent

    广告位与当前视口之间的最小距离,达到此距离后我们才会呈现广告。这样可以预提取广告,但会等待呈现和下载其他子资源。该值的作用与 fetchMarginPercent 类似,表示视口百分比。
  • mobileScaling

    应用于移动设备上边距的乘数。这样,移动设备和桌面设备上的边距就可以有所不同。例如,如果值为 2.0,则移动设备上的所有边距都会乘以 2,从而增加广告位在提取和呈现之前可以达到的最小距离。

enableSingleRequest

enableSingleRequest(): boolean
启用单一请求模式,以便同时提取多个广告。这要求在启用 PubAdsService 之前,先定义所有 Publisher Ads 广告位并将其添加到该服务中。必须在启用服务之前设置单一请求模式。
另请参阅
返回
boolean如果已启用单一请求模式,则返回 true;如果无法启用单一请求模式(因为在启用服务后调用了该方法),则返回 false。

enableVideoAds

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

get

get(key: string): string
返回与给定键关联的 AdSense 属性的值。
示例

JavaScript

googletag.setConfig({
  adsenseAttributes: {
    page_url: "http://www.example.com",
  },
});

const adsenseConfig = googletag.getConfig("adsenseAttributes").adsenseAttributes;
const pageUrl = adsenseConfig?.page_url || null;
// Returns 'http://www.example.com'.

JavaScript(旧版)

googletag.setConfig({
  adsenseAttributes: {
    page_url: "http://www.example.com",
  },
});

var adsenseConfig = googletag.getConfig("adsenseAttributes").adsenseAttributes;
var pageUrl =
  (adsenseConfig === null || adsenseConfig === void 0 ? void 0 : adsenseConfig.page_url) || null;
// Returns 'http://www.example.com'.

TypeScript

googletag.setConfig({
  adsenseAttributes: {
    page_url: "http://www.example.com",
  },
});

const adsenseConfig = googletag.getConfig("adsenseAttributes").adsenseAttributes;
const pageUrl = adsenseConfig?.page_url || null;
// Returns 'http://www.example.com'.
另请参阅
参数
key: string要查找的属性的名称。
返回
string属性键的当前值;如果键不存在,则为 null。

getAttributeKeys

getAttributeKeys(): string[]
返回已在此服务上设置的属性键。
示例

JavaScript

googletag.setConfig({
  adsenseAttributes: {
    page_url: "http://www.example.com",
    document_language: "en",
  },
});

const adsenseConfig = googletag.getConfig("adsenseAttributes").adsenseAttributes;
const adsenseAttributes = Object.keys(adsenseConfig || {});
// Returns ['page_url', 'document_language'].

JavaScript(旧版)

googletag.setConfig({
  adsenseAttributes: {
    page_url: "http://www.example.com",
    document_language: "en",
  },
});

var adsenseConfig = googletag.getConfig("adsenseAttributes").adsenseAttributes;
var adsenseAttributes = Object.keys(adsenseConfig || {});
// Returns ['page_url', 'document_language'].

TypeScript

googletag.setConfig({
  adsenseAttributes: {
    page_url: "http://www.example.com",
    document_language: "en",
  },
});

const adsenseConfig = googletag.getConfig("adsenseAttributes").adsenseAttributes;
const adsenseAttributes = Object.keys(adsenseConfig || {});
// Returns ['page_url', 'document_language'].
返回
string[]在此服务上设置的属性键数组。顺序未定义。

getTargeting

getTargeting(key: string): string[]
返回已设置的特定自定义服务级定位参数。
示例

JavaScript

googletag.setConfig({
  targeting: {
    interests: "sports",
  },
});

const targetingConfig = googletag.getConfig("targeting").targeting;

// Get targeting for a specific key.
const targeting = targetingConfig?.["interests"] || [];
// Returns ['sports'].

const ageTargeting = targetingConfig?.["age"] || [];
// Returns [] (empty array).

JavaScript(旧版)

googletag.setConfig({
  targeting: {
    interests: "sports",
  },
});

var targetingConfig = googletag.getConfig("targeting").targeting;

// Get targeting for a specific key.
var targeting =
  (targetingConfig === null || targetingConfig === void 0
    ? void 0
    : targetingConfig["interests"]) || [];
// Returns ['sports'].

var ageTargeting =
  (targetingConfig === null || targetingConfig === void 0 ? void 0 : targetingConfig["age"]) || [];
// Returns [] (empty array).

TypeScript

googletag.setConfig({
  targeting: {
    interests: "sports",
  },
});

const targetingConfig = googletag.getConfig("targeting").targeting;

// Get targeting for a specific key.
const targeting = targetingConfig?.["interests"] || [];
// Returns ['sports'].

const ageTargeting = targetingConfig?.["age"] || [];
// Returns [] (empty array).
参数
key: string要查找的定位键。
返回
string[]与此键关联的值;如果不存在此类键,则返回空数组。

getTargetingKeys

getTargetingKeys(): string[]
返回已设置的所有自定义服务级定位键的列表。
示例

JavaScript

googletag.setConfig({
  targeting: {
    interests: "sports",
    colors: "blue",
  },
});

const targetingConfig = googletag.getConfig("targeting").targeting;
const keys = Object.keys(targetingConfig || {});
// Returns ['interests', 'colors'].

JavaScript(旧版)

googletag.setConfig({
  targeting: {
    interests: "sports",
    colors: "blue",
  },
});

var targetingConfig = googletag.getConfig("targeting").targeting;
var keys = Object.keys(targetingConfig || {});
// Returns ['interests', 'colors'].

TypeScript

googletag.setConfig({
  targeting: {
    interests: "sports",
    colors: "blue",
  },
});

const targetingConfig = googletag.getConfig("targeting").targeting;
const keys = Object.keys(targetingConfig || {});
// Returns ['interests', 'colors'].
返回
string[]定位键数组。顺序未定义。

isInitialLoadDisabled

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

刷新

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

为了在所有浏览器中都能正常运行,必须先调用 display 广告位,然后才能调用 refresh。如果省略对 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[]要刷新的广告位。数组是可选的;如果未指定,则所有广告位都会刷新。
Optional options: {
  changeCorrelator: boolean;
}
与此刷新调用关联的配置选项。
  • changeCorrelator

    指定是否要生成新的相关因子来提取广告。我们的广告服务器会短暂保留此 Correlator 值(目前为 30 秒,但可能会发生变化),以便将收到的具有相同 Correlator 值的请求视为同一次网页浏览。默认情况下,每次刷新都会生成一个新的相关器。

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

registerRequestHook

registerRequestHook(hook: RequestHook, hookId: string): (() => void)
Experimental 注册一个钩子,以便在全局超时时间内,在页面上的每个广告请求之前与其他已注册的钩子并行执行。
示例

JavaScript

// Register a request hook.
const unregister = googletag.pubads().registerRequestHook(async ({ slots }) => {
  const someAsynchronousAction = Promise.resolve();
  await someAsynchronousAction;
  for (const slot of slots) {
    slot.setConfig({ targeting: { hookApplied: "true" } });
  }
}, "my-hook");

// Unregister the hook.
unregister();

JavaScript(旧版)

// Coming soon.

TypeScript

// Register a request hook.
const unregister = googletag.pubads().registerRequestHook(async ({ slots }) => {
  const someAsynchronousAction = Promise.resolve();
  await someAsynchronousAction;
  for (const slot of slots) {
    slot.setConfig({ targeting: { hookApplied: "true" } });
  }
}, "my-hook");

// Unregister the hook.
unregister();
参数
hook: RequestHook一个函数,它接受一个包含所请求广告位列表的对象,并返回一个在所有异步操作完成后解析的 promise。
hookId: string用于标记钩子的 ID,以便改进诊断。
返回
(() => void)用于取消注册钩子的函数。

set

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

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

JavaScript

googletag.setConfig({
  adsenseAttributes: {
    page_url: "http://www.example.com",
  },
});

JavaScript(旧版)

googletag.setConfig({
  adsenseAttributes: {
    page_url: "http://www.example.com",
  },
});

TypeScript

googletag.setConfig({
  adsenseAttributes: {
    page_url: "http://www.example.com",
  },
});
另请参阅
参数
key: string属性的名称。
value: string属性值。
返回
PubAdsService调用该方法的 Service 对象。

setCategoryExclusion

setCategoryExclusion(categoryExclusion: string): PubAdsService
为给定标签名称设置网页级广告类别排除。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

// Label = AirlineAd.
googletag.setConfig({
  categoryExclusion: ["AirlineAd"],
});
另请参阅
参数
categoryExclusion: string要添加的广告类别排除标签。
返回
PubAdsService调用该方法的 Service 对象。

setCentering

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

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

JavaScript

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

JavaScript(旧版)

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

TypeScript

// Make ads centered.
googletag.setConfig({
  centering: 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.setConfig({
  safeFrame: {
    forceSafeFrame: true,
  },
});

// The following slot will be opted-out of the page-level force
// SafeFrame instruction.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")
  .setConfig({
    safeFrame: {
      forceSafeFrame: 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.setConfig({
  safeFrame: {
    forceSafeFrame: true,
  },
});

// The following slot will be opted-out of the page-level force
// SafeFrame instruction.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")
  .setConfig({
    safeFrame: {
      forceSafeFrame: 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.setConfig({
  safeFrame: {
    forceSafeFrame: true,
  },
});

// The following slot will be opted-out of the page-level force
// SafeFrame instruction.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")!
  .setConfig({
    safeFrame: {
      forceSafeFrame: 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调用该方法的 Service 对象。

setLocation

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

JavaScript

// Postal code:
googletag.setConfig({
  location: "10001,US",
});

JavaScript(旧版)

// Postal code:
googletag.setConfig({
  location: "10001,US",
});

TypeScript

// Postal code:
googletag.setConfig({
  location: "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。长度必须介于 22 到 150 个字符之间。
返回
PubAdsService调用该方法的服务对象。

setSafeFrameConfig

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

这些网页级偏好设置将被广告位级偏好设置(如果已指定)覆盖。
示例

JavaScript

googletag.setConfig({
  safeFrame: {
    forceSafeFrame: true,
    allowOverlayExpansion: true,
    allowPushExpansion: true,
    sandbox: true,
  },
});

googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")
  .setConfig({
    safeFrame: {
      allowOverlayExpansion: false,
    },
  })
  .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.setConfig({
  safeFrame: {
    forceSafeFrame: true,
    allowOverlayExpansion: true,
    allowPushExpansion: true,
    sandbox: true,
  },
});

googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")
  .setConfig({
    safeFrame: {
      allowOverlayExpansion: false,
    },
  })
  .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.setConfig({
  safeFrame: {
    forceSafeFrame: true,
    allowOverlayExpansion: true,
    allowPushExpansion: true,
    sandbox: true,
  },
});

googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")!
  .setConfig({
    safeFrame: {
      allowOverlayExpansion: false,
    },
  })
  .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
为给定键设置适用于所有发布商广告服务广告位的自定义定位参数。如果针对同一键多次调用此方法,则会覆盖旧值。这些键在您的 Google Ad Manager 账号中定义。
示例

JavaScript

// Example with a single value for a key.
googletag.setConfig({
  targeting: {
    interests: "sports",
  },
});

// Example with multiple values for a key inside in an array.
googletag.setConfig({
  targeting: {
    interests: ["sports", "music"],
  },
});

JavaScript(旧版)

// Example with a single value for a key.
googletag.setConfig({
  targeting: {
    interests: "sports",
  },
});

// Example with multiple values for a key inside in an array.
googletag.setConfig({
  targeting: {
    interests: ["sports", "music"],
  },
});

TypeScript

// Example with a single value for a key.
googletag.setConfig({
  targeting: {
    interests: "sports",
  },
});

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

setVideoContent

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

updateCorrelator

updateCorrelator(): PubAdsService
更改随广告请求发送的相关因子,从而有效启动新的网页浏览。对于源于同一次网页浏览的所有广告请求,Correlator 值都相同,但对于不同的网页浏览,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.RequestHook

通过 PubAdsService.registerRequestHook 注册后,在每个广告请求之前调用的回调函数。

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
奖励中包含的物品类型(例如“金币”)。
另请参阅

属性


amount

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

type

type: string
奖励中包含的物品类型(例如“金币”)。

googletag.Service

包含所有服务通用方法的基础服务类。
方法
addEventListener
注册一个监听器,以便您在网页上发生特定 GPT 事件时设置并调用 JavaScript 函数。
getSlots
获取与此服务关联的时段列表。
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调用该方法的 Service 对象。

getSlots

getSlots(): Slot[]
获取与此服务关联的时段列表。
返回
Slot[]槽位会按照添加到服务中的顺序执行。

removeEventListener

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

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

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
添加从单尺寸数组(表示视口)到单尺寸或多尺寸数组(表示广告位)的映射。
示例

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
向此槽添加 Service。
clearCategoryExclusions
已弃用。 清除此广告位的所有广告位级广告类别排除标签。
clearTargeting
已弃用。 清除此广告位的特定或所有自定义广告位级定位参数。
defineSizeMapping
为此广告位设置从最小视口尺寸到广告位尺寸的映射数组。
get
已弃用。 返回与此广告位的给定键关联的 AdSense 属性的值。
getAdUnitPath
返回广告单元的完整路径,其中包含广告资源网代码和广告单元路径。
getAttributeKeys
已弃用。 返回在此广告位上设置的属性键列表。
getCategoryExclusions
已弃用。 返回此广告位的广告类别排除标签。
getConfig
获取由 setConfig 设置的广告位的常规配置选项的冻结副本。
getResponseInformation
返回广告响应信息。
getSlotElementId
返回定义槽位时提供的槽位 div 的 ID。
getTargeting
已弃用。 返回在此广告位上设置的特定自定义定位参数。
getTargetingKeys
已弃用。 返回在此广告位上设置的所有自定义定位键的列表。
set
已弃用。 为此广告位上的 AdSense 属性设置值。
setCategoryExclusion
已弃用。 在此广告位上设置广告位级广告类别排除标签。
setClickUrl
已弃用。 设置用户点击广告后将被重定向到的点击跟踪网址。
setCollapseEmptyDiv
已弃用。 设置当广告位 div 中没有广告时是否应隐藏该广告位。
setConfig
为此广告位设置常规配置选项。
setForceSafeFrame
已弃用。 配置是否应强制使用 SafeFrame 容器呈现此广告位中的广告。
setSafeFrameConfig
已弃用。 设置 SafeFrame 配置的广告位级偏好设置。
setTargeting
已弃用。 为此广告位设置自定义定位参数。
updateTargetingFromMap
已弃用。 通过 JSON 对象中的键值对映射为此广告位设置自定义定位参数。

方法


addService

addService(service: Service): 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调用该方法的广告位对象。

clearCategoryExclusions

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

JavaScript

// Set category exclusion to exclude ads with 'AirlineAd' labels.
const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setConfig({
    categoryExclusion: ["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.setConfig({
  categoryExclusion: null,
});

// 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")
  .setConfig({
    categoryExclusion: ["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.setConfig({
  categoryExclusion: null,
});

// 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")!
  .setConfig({
    categoryExclusion: ["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.setConfig({
  categoryExclusion: null,
});

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

clearTargeting

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

JavaScript

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

slot.setConfig({
  targeting: {
    color: null,
  },
});
// Targeting 'allow_expandable' and 'interests' are still present,
// while 'color' was cleared.

slot.setConfig({
  targeting: null,
});
// All targeting has been cleared.

JavaScript(旧版)

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

slot.setConfig({
  targeting: {
    color: null,
  },
});
// Targeting 'allow_expandable' and 'interests' are still present,
// while 'color' was cleared.

slot.setConfig({
  targeting: null,
});
// All targeting has been cleared.

TypeScript

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

slot.setConfig({
  targeting: {
    color: null,
  },
});
// Targeting 'allow_expandable' and 'interests' are still present,
// while 'color' was cleared.

slot.setConfig({
  targeting: null,
});
// All targeting has been cleared.
另请参阅
参数
Optional key: string定位参数键。该键是可选的;如果未指定,所有定位参数都将被清除。
返回
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 创建它。每个尺寸映射都是一个包含两个元素的数组:SingleSizeArray 和 GeneralSize。
返回
Slot调用该方法的广告位对象。

get

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

JavaScript

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setConfig({
    adsenseAttributes: {
      page_url: "http://www.example.com",
    },
  })
  .addService(googletag.pubads());

const adsenseConfig = slot.getConfig("adsenseAttributes").adsenseAttributes;
const pageUrl = adsenseConfig?.page_url || null;
// Returns 'http://www.example.com'.

JavaScript(旧版)

var slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setConfig({
    adsenseAttributes: {
      page_url: "http://www.example.com",
    },
  })
  .addService(googletag.pubads());

var adsenseConfig = slot.getConfig("adsenseAttributes").adsenseAttributes;
var pageUrl =
  (adsenseConfig === null || adsenseConfig === void 0 ? void 0 : adsenseConfig.page_url) || null;
// Returns 'http://www.example.com'.

TypeScript

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setConfig({
    adsenseAttributes: {
      page_url: "http://www.example.com",
    },
  })
  .addService(googletag.pubads());

const adsenseConfig = slot.getConfig("adsenseAttributes").adsenseAttributes;
const pageUrl = adsenseConfig?.page_url || null;
// Returns 'http://www.example.com'.
另请参阅
参数
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[]
返回在此广告位上设置的属性键列表。如需查看此广告位继承的服务级属性的键,请使用 PubAdsService.getAttributeKeys。
示例

JavaScript

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setConfig({
    adsenseAttributes: {
      page_url: "http://www.example.com",
      document_language: "en",
    },
  })
  .addService(googletag.pubads());

const adsenseConfig = slot.getConfig("adsenseAttributes").adsenseAttributes;
const adsenseAttributes = Object.keys(adsenseConfig || {});
// Returns ['page_url', 'document_language'].

JavaScript(旧版)

var slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setConfig({
    adsenseAttributes: {
      page_url: "http://www.example.com",
      document_language: "en",
    },
  })
  .addService(googletag.pubads());

var adsenseConfig = slot.getConfig("adsenseAttributes").adsenseAttributes;
var adsenseAttributes = Object.keys(adsenseConfig || {});
// Returns ['page_url', 'document_language'].

TypeScript

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setConfig({
    adsenseAttributes: {
      page_url: "http://www.example.com",
      document_language: "en",
    },
  })
  .addService(googletag.pubads());

const adsenseConfig = slot.getConfig("adsenseAttributes").adsenseAttributes;
const adsenseAttributes = Object.keys(adsenseConfig || {});
// Returns ['page_url', 'document_language'].
返回
string[]属性键数组。顺序未定义。

getCategoryExclusions

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

JavaScript

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setConfig({
    categoryExclusion: ["AirlineAd", "TrainAd"],
  })
  .addService(googletag.pubads());

const exclusions = slot.getConfig("categoryExclusion")?.categoryExclusion || [];
// Returns ['AirlineAd', 'TrainAd'].

JavaScript(旧版)

var _a;
var slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setConfig({
    categoryExclusion: ["AirlineAd", "TrainAd"],
  })
  .addService(googletag.pubads());

var exclusions =
  ((_a = slot.getConfig("categoryExclusion")) === null || _a === void 0
    ? void 0
    : _a.categoryExclusion) || [];
// Returns ['AirlineAd', 'TrainAd'].

TypeScript

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

const exclusions = slot.getConfig("categoryExclusion")?.categoryExclusion || [];
// Returns ['AirlineAd', 'TrainAd'].
返回
string[]此广告位的广告类别排除标签;如果未设置任何标签,则为空数组。

getConfig

getConfig(keys: string | string[]): Readonly<Pick<SlotSettingsConfig, "adsenseAttributes" | "targeting" | "categoryExclusion">>
获取由 setConfig 设置的广告位常规配置选项的冻结副本。

此方法不支持所有 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[]要获取的配置选项的键。
返回
Readonly<Pick<SlotSettingsConfig, "adsenseAttributes" | "targeting" | "categoryExclusion">>广告位的配置选项的冻结副本。

getResponseInformation

getResponseInformation(): ResponseInformation
返回广告响应信息。这是根据广告位的最后一次广告响应得出的。如果在广告位没有广告时调用此方法,则会返回 null。
返回
ResponseInformation最新的广告响应信息;如果广告位没有广告,则为 null。

getSlotElementId

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

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")
  .setConfig({
    targeting: {
      allow_expandable: "true",
    },
  })
  .addService(googletag.pubads());

const targetingConfig = slot.getConfig("targeting").targeting;

// Get targeting for a specific key.
const targeting = targetingConfig?.["allow_expandable"] || [];
// Returns ['true'].

const ageTargeting = targetingConfig?.["age"] || [];
// Returns [] (empty array).

JavaScript(旧版)

var slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setConfig({
    targeting: {
      allow_expandable: "true",
    },
  })
  .addService(googletag.pubads());

var targetingConfig = slot.getConfig("targeting").targeting;

// Get targeting for a specific key.
var targeting =
  (targetingConfig === null || targetingConfig === void 0
    ? void 0
    : targetingConfig["allow_expandable"]) || [];
// Returns ['true'].

var ageTargeting =
  (targetingConfig === null || targetingConfig === void 0 ? void 0 : targetingConfig["age"]) || [];
// Returns [] (empty array).

TypeScript

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

const targetingConfig = slot.getConfig("targeting").targeting;

// Get targeting for a specific key.
const targeting = targetingConfig?.["allow_expandable"] || [];
// Returns ['true'].

const ageTargeting = targetingConfig?.["age"] || [];
// Returns [] (empty array).
参数
key: string要查找的定位键。
返回
string[]与此键关联的值;如果不存在此类键,则返回空数组。

getTargetingKeys

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

JavaScript

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

const targetingConfig = slot.getConfig("targeting").targeting;
const keys = Object.keys(targetingConfig || {});
// Returns ['interests', 'allow_expandable'].

JavaScript(旧版)

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

var targetingConfig = slot.getConfig("targeting").targeting;
var keys = Object.keys(targetingConfig || {});
// Returns ['interests', 'allow_expandable'].

TypeScript

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

const targetingConfig = slot.getConfig("targeting").targeting;
const keys = Object.keys(targetingConfig || {});
// Returns ['interests', 'allow_expandable'].
返回
string[]定位键数组。顺序未定义。

set

set(key: string, value: string): Slot
为此广告位上的 AdSense 属性设置值。这将覆盖在服务级别为此键设置的所有值。

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

JavaScript

// Setting an attribute on a single ad slot.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setConfig({
    adsenseAttributes: {
      page_url: "http://www.example.com",
    },
  })
  .addService(googletag.pubads());

JavaScript(旧版)

// Setting an attribute on a single ad slot.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setConfig({
    adsenseAttributes: {
      page_url: "http://www.example.com",
    },
  })
  .addService(googletag.pubads());

TypeScript

// Setting an attribute on a single ad slot.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setConfig({
    adsenseAttributes: {
      page_url: "http://www.example.com",
    },
  })
  .addService(googletag.pubads());
另请参阅
参数
key: string属性的名称。
value: string属性值。
返回
Slot调用该方法的广告位对象。

setCategoryExclusion

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

JavaScript

// Label = AirlineAd.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setConfig({
    categoryExclusion: ["AirlineAd"],
  })
  .addService(googletag.pubads());

JavaScript(旧版)

// Label = AirlineAd.
googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .setConfig({
    categoryExclusion: ["AirlineAd"],
  })
  .addService(googletag.pubads());

TypeScript

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

setClickUrl

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

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

JavaScript

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

JavaScript(旧版)

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

TypeScript

googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setConfig({
    clickUrl: "http://www.example.com?original_click_url=",
  })
  .addService(googletag.pubads());
参数
value: string要设置的点击跟踪网址。
返回
Slot调用该方法的广告位对象。

setCollapseEmptyDiv

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

JavaScript

const slot1 = googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")
  .setConfig({
    collapseDiv: "BEFORE_FETCH",
  })
  .addService(googletag.pubads());
// The above will cause the div for this slot to be collapsed
// when the page is loaded, before ads are requested.

const slot2 = googletag
  .defineSlot("/1234567/sports", [160, 600], "div-2")
  .setConfig({
    collapseDiv: "ON_NO_FILL",
  })
  .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(旧版)

var slot1 = googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")
  .setConfig({
    collapseDiv: "BEFORE_FETCH",
  })
  .addService(googletag.pubads());
// The above will cause the div for this slot to be collapsed
// when the page is loaded, before ads are requested.

var slot2 = googletag
  .defineSlot("/1234567/sports", [160, 600], "div-2")
  .setConfig({
    collapseDiv: "ON_NO_FILL",
  })
  .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

const slot1 = googletag
  .defineSlot("/1234567/sports", [160, 600], "div-1")!
  .setConfig({
    collapseDiv: "BEFORE_FETCH",
  })
  .addService(googletag.pubads());
// The above will cause the div for this slot to be collapsed
// when the page is loaded, before ads are requested.

const slot2 = googletag
  .defineSlot("/1234567/sports", [160, 600], "div-2")!
  .setConfig({
    collapseDiv: "ON_NO_FILL",
  })
  .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调用该方法的广告位对象。

setConfig

setConfig(slotConfig: SlotSettingsConfig): Slot
为此广告位设置常规配置选项。
参数
slotConfig: SlotSettingsConfig配置对象。
返回
Slot调用该方法的广告位对象。

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调用该方法的广告位对象。

setSafeFrameConfig

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

如果指定了这些广告位级偏好设置,它们将覆盖所有网页级偏好设置。
示例

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调用该方法的广告位对象。

setTargeting

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

JavaScript

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

// Example with a single value for a key.
slot.setConfig({
  targeting: {
    allow_expandable: "true",
  },
});

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

JavaScript(旧版)

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

// Example with a single value for a key.
slot.setConfig({
  targeting: {
    allow_expandable: "true",
  },
});

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

TypeScript

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

// Example with a single value for a key.
slot.setConfig({
  targeting: {
    allow_expandable: "true",
  },
});

// Example with multiple values for a key inside in an array.
slot.setConfig({
  targeting: {
    interests: ["sports", "music"],
  },
});
另请参阅
参数
key: string定位参数键。
value: string | string[]定位参数值或值数组。
返回
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调用该方法的广告位对象。

googletag.config

页面级设置的主配置界面。
接口
AdExpansionConfig
用于控制广告展开的设置。
AdSenseAttributesConfig
用于控制 AdSense 广告行为的设置。
AutoRefreshConfig
自动刷新配置设置。
ContinueButtonConfig
用于配置“继续”按钮行为的设置。
InterstitialConfig
一个对象,用于定义单个插页式广告位的行为。
LazyLoadConfig
用于控制在 GPT 中使用延迟加载的设置。
PageSettingsConfig
页面级设置的主配置界面。
PrivacyTreatmentsConfig
用于控制发布商隐私权处理方式的设置。
PublisherProvidedSignalsConfig
发布商提供的信号 (PPS) 配置对象。
SafeFrameConfig
用于控制 GPT 中的 SafeFrame 的设置。
SlotSettingsConfig
用于广告位级设置的主配置界面。
TaxonomyData
一个包含单个类目的值的对象。
VideoAdsConfig
用于配置视频广告相关设置的设置。
类型别名
CollapseDivBehavior
用于控制广告位收起行为的支持值。
InterstitialTrigger
支持的插页式广告触发器。
PrivacyTreatment
支持的发布商隐私保护处理措施。
Taxonomy

类型别名


CollapseDivBehavior

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

InterstitialTrigger

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

注意:自 2026 年 6 月 15 日起,backward 触发器将不再受支持,启用它不会产生任何效果。如需了解详情,请参阅 GPT 版本说明。

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

自动刷新配置设置。
属性
backForwardCache?
当网页从往返缓存中恢复时,GPT 是否会自动刷新正在被浏览的广告位。
heavyAds?
如果 Chrome 的重度广告干预机制在广告 iframe 上触发,GPT 是否会自动刷新广告位。

属性


Optional backForwardCache

backForwardCache?: boolean
当网页从往返缓存中恢复时,GPT 是否会自动刷新正在被浏览的广告位。默认值为 true。
示例

JavaScript

// Set the auto refresh configuration, disabling auto refresh on
// back/forward cache restore.
googletag.setConfig({ autoRefresh: { backForwardCache: false } });

// Clear the auto refresh configuration, restoring to default behavior.
googletag.setConfig({ autoRefresh: null });

JavaScript(旧版)

// Set the auto refresh configuration, disabling auto refresh on
// back/forward cache restore.
googletag.setConfig({ autoRefresh: { backForwardCache: false } });

// Clear the auto refresh configuration, restoring to default behavior.
googletag.setConfig({ autoRefresh: null });

TypeScript

// Set the auto refresh configuration, disabling auto refresh on
// back/forward cache restore.
googletag.setConfig({ autoRefresh: { backForwardCache: false } });

// Clear the auto refresh configuration, restoring to default behavior.
googletag.setConfig({ autoRefresh: null });
另请参阅

Optional heavyAds

heavyAds?: boolean
如果 Chrome 的重度广告干预机制在广告 iframe 上触发,GPT 是否会自动刷新广告位。默认值为 true。
示例

JavaScript

// Set the auto refresh configuration, disabling auto refresh on heavy
// ad intervention.
googletag.setConfig({ autoRefresh: { heavyAds: false } });

// Clear the auto refresh configuration, restoring to default behavior.
googletag.setConfig({ autoRefresh: null });

JavaScript(旧版)

// Set the auto refresh configuration, disabling auto refresh on heavy
// ad intervention.
googletag.setConfig({ autoRefresh: { heavyAds: false } });

// Clear the auto refresh configuration, restoring to default behavior.
googletag.setConfig({ autoRefresh: null });

TypeScript

// Set the auto refresh configuration, disabling auto refresh on heavy
// ad intervention.
googletag.setConfig({ autoRefresh: { heavyAds: false } });

// Clear the auto refresh configuration, restoring to default behavior.
googletag.setConfig({ autoRefresh: null });
另请参阅

googletag.config.ContinueButtonConfig

用于配置“继续”按钮行为的设置。
属性
backgroundColor?
按钮的背景颜色。
font?
按钮文字的字体系列。
fontColor?
按钮的文字颜色。
freqCapIntervalMinutes?
频次上限间隔时间(以分钟为单位)。
targetId?
要在其上呈现/触发“继续”按钮的 HTML 元素的 ID。
另请参阅

属性


Optional backgroundColor

backgroundColor?: string
按钮的背景颜色。

示例:'blue'、'#94B1FF'

Optional 字体

font?: string
按钮文字的字体系列。

示例:'Arial'

Optional fontColor

fontColor?: string
按钮的文字颜色。

示例:'white'、'#B73B87'

Optional freqCapIntervalMinutes

freqCapIntervalMinutes?: number
频次上限间隔时间(以分钟为单位)。

必须是大于或等于 1 的整数。

Optional targetId

targetId?: string
要在其上呈现/触发“继续”按钮的 HTML 元素的 ID。

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
应用于移动设备上边距的乘数。此调节系数会同时应用于 fetchMarginPercent 和 renderMarginPercent。

这样,您就可以在移动设备和桌面设备上设置不同的边距,因为两者的视口大小和滚动速度可能不同。例如,如果值为 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?
已弃用。 
autoRefresh?
用于配置自动广告刷新行为的设置。
categoryExclusion?
用于配置广告类别排除对象的设置。
centering?
用于控制广告水平居中的设置。
collapseDiv?
用于控制广告位收起行为的设置。
disableInitialLoad?
用于控制何时请求广告的设置。
lazyLoad?
用于控制在 GPT 中使用延迟加载的设置。
location?
用于将订单项地理位置定位到地理位置的设置。
pps?
用于控制发布商提供的信号 (PPS) 的设置。
privacyTreatments?
用于控制发布商隐私权处理方式的设置。
requestHookTimeoutMs?
此设置用于控制 GPT 在继续发出广告请求之前,等待所有已注册的请求钩子完成的最长时间。
safeFrame?
用于控制在 GPT 中使用 SafeFrame 的设置。
singleRequest?
用于启用或停用单一请求架构 (SRA) 的设置。
targeting?
用于控制键值对定位的设置。
threadYield?
用于控制 GPT 在请求和呈现广告素材时是否应让出 JS 线程的设置。
videoAds?
用于控制视频广告的设置。

属性


Optional adExpansion

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

Optional adsenseAttributes

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

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

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

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

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 autoRefresh

autoRefresh?: AutoRefreshConfig
用于配置自动广告刷新行为的设置。
示例

JavaScript

// Set the auto refresh configuration.
googletag.setConfig({ autoRefresh: { heavyAds: false } });

// Clear the auto refresh configuration.
googletag.setConfig({ autoRefresh: null });

JavaScript(旧版)

// Set the auto refresh configuration.
googletag.setConfig({ autoRefresh: { heavyAds: false } });

// Clear the auto refresh configuration.
googletag.setConfig({ autoRefresh: null });

TypeScript

// Set the auto refresh configuration.
googletag.setConfig({ autoRefresh: { heavyAds: false } });

// Clear the auto refresh configuration.
googletag.setConfig({ autoRefresh: null });

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.display 或 PubAdsService.refresh 之前调用此方法。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

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() 方法时为已注册的广告位请求广告。而是必须单独调用 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?: 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 Experimental requestHookTimeoutMs

requestHookTimeoutMs?: number | "auto"
此设置用于控制 GPT 在继续处理广告请求之前,等待所有已注册的请求钩子完成的最长时间。

所有已注册的请求钩子都会并行执行。此超时时间定义了广告请求流程在等待这些并行执行完成时将暂停的时长上限。

支持的值:
  • 正数(以毫秒为单位):自定义等待期。
  • 'auto':GPT 使用 Google 优化的超时。
  • null:停用超时(GPT 会无限期等待钩子完成)。
示例

JavaScript

// Set a 1000ms timeout for request hooks.
googletag.setConfig({ requestHookTimeoutMs: 1000 });

// Use a Google-optimized timeout for request hooks.
googletag.setConfig({ requestHookTimeoutMs: "auto" });

// Clear the timeout.
googletag.setConfig({ requestHookTimeoutMs: null });

JavaScript(旧版)

// Set a 1000ms timeout for request hooks.
googletag.setConfig({ requestHookTimeoutMs: 1000 });

// Use a Google-optimized timeout for request hooks.
googletag.setConfig({ requestHookTimeoutMs: "auto" });

// Clear the timeout.
googletag.setConfig({ requestHookTimeoutMs: null });

TypeScript

// Set a 1000ms timeout for request hooks.
googletag.setConfig({ requestHookTimeoutMs: 1000 });

// Use a Google-optimized timeout for request hooks.
googletag.setConfig({ requestHookTimeoutMs: "auto" });

// Clear the timeout.
googletag.setConfig({ requestHookTimeoutMs: null });

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.display 或 PubAdsService.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 的浏览器让出 JS 线程。

支持的值:
  • 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
包含分类映射的对象,或 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>>
包含分类映射的对象,或 null(用于清除配置)。

googletag.config.SafeFrameConfig

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

属性


Optional allowOverlayExpansion

allowOverlayExpansion?: boolean
SafeFrame 是否应允许广告内容通过覆盖网页内容来展开。

Optional allowPushExpansion

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

Optional forceSafeFrame

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

Optional 沙盒

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

Optional useUniqueDomain

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

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

googletag.config.SlotSettingsConfig

用于插槽级设置的主配置接口。

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

下面列出的所有属性均为示例,并不反映利用 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?
用于配置广告位收起行为的设置。
continueButton?
用于配置内容暂停时广告的“继续”按钮行为的设置。
interstitial?
用于配置插页式广告位行为的设置。
safeFrame?
用于在 GPT 中配置 SafeFrame 使用情况的设置。
targeting?
用于配置键值对定位的设置。

属性


Optional adExpansion

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

Optional adsenseAttributes

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

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

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

JavaScript

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

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

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

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

JavaScript(旧版)

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

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

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

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

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 continueButton

continueButton?: ContinueButtonConfig
用于配置内容暂停时广告的继续按钮行为的设置。

这些设置允许自定义与内容暂停格式关联的退出和继续阅读互动的显示效果和行为。

调用 setConfig() 时未指定的任何继续按钮设置都将使用 Google 设置的默认值。

如需停用或清除所有继续按钮设置,请传递 null。
示例

JavaScript

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .addService(googletag.pubads());
// Configure continue button settings.
slot.setConfig({
  continueButton: {
    font: "Arial",
    fontColor: "white",
    backgroundColor: "blue",
    targetId: "target-div-id",
    freqCapIntervalMinutes: 20,
  },
});

// Clear continue button settings.
slot.setConfig({ continueButton: null });

JavaScript(旧版)

var slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .addService(googletag.pubads());
// Configure continue button settings.
slot.setConfig({
  continueButton: {
    font: "Arial",
    fontColor: "white",
    backgroundColor: "blue",
    targetId: "target-div-id",
    freqCapIntervalMinutes: 20,
  },
});

// Clear continue button settings.
slot.setConfig({ continueButton: null });

TypeScript

const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .addService(googletag.pubads());
// Configure continue button settings.
slot.setConfig({
  continueButton: {
    font: "Arial",
    fontColor: "white",
    backgroundColor: "blue",
    targetId: "target-div-id",
    freqCapIntervalMinutes: 20,
  },
});

// Clear continue button settings.
slot.setConfig({ continueButton: null });

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
Taxonomy 值列表。

属性


值

values: readonly string[]
Taxonomy 值列表。

googletag.config.VideoAdsConfig

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

属性


enableVideoAds

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

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

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

Optional videoCmsId

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

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

Optional videoContentId

videoContentId?: string
视频内容 ID。

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

googletag.enums

这是 GPT 用于枚举类型的命名空间。
枚举
OutOfPageFormat
GPT 支持的页外广告格式。
TagForAgeTreatment
GPT 支持的年龄处理方式设置。
TrafficSource
GPT 支持的流量来源。

枚举


OutOfPageFormat

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

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

TagForAgeTreatment

TagForAgeTreatment
GPT 支持的年龄处理方式设置。
另请参阅
枚举成员
CHILD
表示广告请求应采用“面向儿童的内容”年龄分级保护标记。
TEEN
表示广告请求应采用“面向青少年的内容”年龄分级保护标记。
UNSPECIFIED
默认值。表示没有适用于广告请求的特定年龄限制处理信号。

TrafficSource

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

googletag.events

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

googletag.events.Event

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

属性


serviceName

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

slot

slot: Slot
触发事件的槽。

googletag.events.EventTypeMap

这是一种伪类型,用于将事件名称映射到其对应的事件对象类型,以便 Service.addEventListener 和 Service.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
触发事件的槽。
示例

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
触发事件的槽。
方法
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(): boolean
向用户展示游戏手动插页式广告。返回广告是否已成功展示。
返回
boolean

googletag.events.ImpressionViewableEvent

扩展 Event
当展示根据 Active View 条件变为可见时,系统会触发此事件。
属性
serviceName
触发事件的服务的名称。
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
触发事件的槽。
示例

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
触发事件的槽。
示例

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
触发事件的槽。
方法
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(): boolean
展示激励广告。只有在用户同意观看广告后,才能调用此方法。
返回
boolean激励广告是否已成功展示。

googletag.events.RewardedSlotVideoCompletedEvent

扩展 Event
此事件会在激励视频广告播放完毕时触发。
属性
serviceName
触发事件的服务的名称。
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
触发事件的槽。
示例

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
触发事件的槽。
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
当系统为特定广告位请求广告时,会触发此事件。
属性
serviceName
触发事件的服务的名称。
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
触发事件的槽。
示例

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
触发事件的槽。
示例

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

用于为特定出价方或提供商返回安全信号的接口。必须提供 id 或 networkCode,但不能同时提供这两者。

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

返回特定发布商的安全信号。

发布商信号提供商由 2 部分组成:

  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

push(provider: SecureSignalProvider): void
向信号提供商数组添加新的 secureSignals.SecureSignalProvider,并开始信号生成流程。
参数
provider: SecureSignalProvider要添加到数组中的 secureSignals.SecureSignalProvider 对象。