此参考文档使用 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 用于事件的命名空间。 |
secure | 这是 GPT 用于管理安全信号的命名空间。 |
| 接口 | |
|---|---|
Command | 命令数组接受一系列函数,并按顺序调用这些函数。 |
Companion | 随播广告服务。 |
Privacy | 隐私设置的配置对象。 |
Pub | 发布商广告服务。 |
Request | 通过 PubAdsService.registerRequestHook 注册后,在每个广告请求之前调用的回调函数。 |
Response | 表示单个广告响应的对象。 |
Rewarded | 一个对象,表示与激励广告关联的奖励。 |
Service | 包含所有服务通用方法的基础服务类。 |
Size | 尺寸映射规范对象的构建器。 |
Slot | Slot 是一个对象,代表网页上的单个广告位。 |
| 类型别名 | |
|---|---|
Fluid | 尺寸字符串,其中广告容器占据其父级 div 的 100% 宽度,然后调整其高度以适应广告素材内容。 |
General | 广告位的有效尺寸配置,可以是一种或多种尺寸。 |
Multi | 单个有效尺寸的列表。 |
Named | 广告位可以具有的命名尺寸。 |
Single | 广告位的单个有效尺寸。 |
Single | 由两个数字组成的数组,表示 [宽度, 高度]。 |
Size | 视口尺寸与广告尺寸的映射。 |
Size | 尺寸映射列表。 |
| 变量 | |
|---|---|
api | 表示 GPT API 已加载并可供调用的标志。 |
cmd | 对全局命令队列的引用,用于异步执行 GPT 相关调用。 |
pubads | 此标记指示 PubAdsService 已启用、已加载且可完全正常运行。 |
secure | 对安全信号提供商数组的引用。 |
| 函数 | |
|---|---|
companion | 返回对 CompanionAdsService 的引用。 |
define | 使用指定广告单元路径构建页外广告位。 |
define | 使用指定广告单元路径和尺寸构建广告位,并将其与网页上将包含广告的 div 元素的 ID 相关联。 |
destroy | 销毁指定的广告位,从 GPT 中移除这些广告位的所有相关对象和引用。 |
disable | 停用 Google 发布商控制台。 |
display | 指示槽位服务呈现槽位。 |
enable | 启用已为网页上的广告位定义的所有 GPT 服务。 |
get | 获取由 setConfig 设置的页面常规配置选项的冻结副本。 |
get | 返回 GPT 的当前版本。 |
open | 打开 Google 发布商控制台。 |
pubads | 返回对 PubAdsService 的引用。 |
set | 从此时起,为 PubAdsService 创建的所有广告容器 iframe 设置标题。 |
set | 为页面设置常规配置选项。 |
size | 创建新的 SizeMappingBuilder。 |
类型别名
FluidSize
FluidSize: "fluid"GeneralSize
GeneralSize: SingleSize | MultiSizeMultiSize
MultiSize: SingleSize[]NamedSize
SingleSize
SingleSize: SingleSizeArray | NamedSizeSingleSizeArray
SingleSizeArray: [number, number]SizeMapping
SizeMapping: [SingleSizeArray, GeneralSize]SizeMappingArray
SizeMappingArray: SizeMapping[]变量
Const apiReady
apiReady: boolean | undefinedundefined。请注意,处理异步的推荐方法是使用 googletag.cmd 将回调排入队列,以便在 GPT 准备就绪时执行。这些回调无需检查 googletag.apiReady,因为它们在 API 设置完成后一定会执行。
Const cmd
cmd: ((this: typeof globalThis) => void)[] | CommandArraygoogletag.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 | undefinedundefined。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使用指定广告单元路径构建页外广告位。
对于自定义页外广告,
对于 GPT 管理的页外广告,
对于自定义页外广告,
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 | 包含广告资源网代码和广告单元代码的完整广告单元路径。 |
| 将包含此广告单元或 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 | 所添加广告位的宽度和高度。如果未提供自适应尺寸映射,或者视口尺寸小于映射中提供的最小尺寸,则广告请求中会使用此尺寸。 |
| 将包含此广告单元的 div 的 ID。 |
| 返回 | |
|---|---|
Slot | null | 新创建的槽位;如果无法创建槽位,则为 null。 |
destroySlots
destroySlots(slots?: Slot[]): boolean销毁给定广告位,从 GPT 中移除这些广告位的所有相关对象和引用。此 API 不支持回传广告位和随播广告位。
在广告位上调用此 API 会清除广告,并从 GPT 维护的内部状态中移除广告位对象。对槽对象调用任何其他函数都会导致未定义的行为。请注意,如果发布商网页保留了对该广告位的引用,浏览器可能仍不会释放与该广告位关联的内存。调用此 API 会使与该广告位关联的 div 可供重复使用。
具体而言,销毁广告位会从 GPT 的长效网页浏览中移除广告,因此未来的请求不会受到涉及此广告的包版或竞争性排除的影响。如果在从页面中移除广告位的 div 之前未能调用此函数,将会导致未定义的行为。
在广告位上调用此 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();
| 参数 | |
|---|---|
| 要销毁的广告位数组。数组是可选的;如果未指定,则所有广告位都将被销毁。 |
| 返回 | |
|---|---|
boolean | 如果槽位已被销毁,则返回 true,否则返回 false。 |
disablePublisherConsole
disablePublisherConsole(): void停用 Google 发布商控制台。
- 另请参阅
display
display(divOrSlot: string | Element | Slot): void指示槽位服务呈现槽位。每个广告位在每个网页上只能展示一次。所有时段都必须先进行定义并关联服务,然后才能显示。只有在元素存在于 DOM 中时,才能发出显示调用。通常,您可以在方法调用中命名的 div 元素内的脚本块中放置该方法。
如果使用的是单一请求架构 (SRA),则在调用此方法时,系统会一次性提取所有未提取的广告位。如需强制不展示广告位,必须移除整个 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();
- 另请参阅
| 参数 | |
|---|---|
| 广告位 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(): SizeMappingBuildergoogletag.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()); });
| 参数 | |
|---|---|
| 要执行的 JavaScript 函数。运行时绑定始终为 globalThis。请考虑传递箭头函数,以保留封闭词法上下文的 this 值。 |
| 返回 | |
|---|---|
number | 到目前为止已处理的命令数量。这与 Array.push 的返回值(数组的当前长度)兼容。 |
googletag.CompanionAdsService
扩展
Service随播广告服务。视频广告会使用此服务来展示随播广告。
| 方法 | |
|---|---|
add | 注册一个监听器,以便您在网页上发生特定 GPT 事件时设置并调用 JavaScript 函数。 继承自 |
get | 获取与此服务关联的时段列表。 继承自 |
remove | 移除之前注册的监听器。 继承自 |
set | 设置是否对尚未填充的随播广告位进行自动补余。 |
- 另请参阅
方法
setRefreshUnfilledSlots
setRefreshUnfilledSlots(value: boolean): void设置是否对尚未填充的随播广告位进行自动补余。
在网页的生命周期内,可以多次调用此方法来开启和关闭补余。只有同时向 PubAdsService 注册的广告位才会进行补余。由于政策限制,此方法不适用于在投放 Ad Exchange 视频广告时填充空白随播广告位。
在网页的生命周期内,可以多次调用此方法来开启和关闭补余。只有同时向 PubAdsService 注册的广告位才会进行补余。由于政策限制,此方法不适用于在投放 Ad Exchange 视频广告时填充空白随播广告位。
- 示例
JavaScript
googletag.companionAds().setRefreshUnfilledSlots(true);
JavaScript(旧版)
googletag.companionAds().setRefreshUnfilledSlots(true);
TypeScript
googletag.companionAds().setRefreshUnfilledSlots(true);
| 参数 | |
|---|---|
value: boolean | true 可自动补余未填充的广告位,false 可让其保持不变。 |
googletag.PrivacySettingsConfig
隐私设置的配置对象。
| 属性 | |
|---|---|
child | 指明是否应将网页视为面向儿童的内容。 |
limited | 使广告投放能够在受限广告模式下运行,以帮助发布商满足监管合规需求。 |
non | 使广告投放能够在非个性化广告模式下运行,以帮助发布商满足监管合规需求。 |
restrict | 使广告投放能够在受限数据处理模式下运行,以帮助发布商满足监管合规需求。 |
tag | 年龄限制处理方式,用于指明广告请求是否应被视为面向儿童、青少年或年龄不明的用户。 |
traffic | 指明请求代表的是所购流量还是自然流量。 |
under | 指明是否将广告请求标记为来自未达到同意年龄的用户。 |
- 另请参阅
属性
Optional childDirectedTreatment
Optional limitedAds
limitedAds?: boolean您可以通过以下两种方式指示 GPT 请求受限广告:
- 自动:使用来自 IAB TCF v2.0 意见征求管理平台的信号。
- 手动,方法是将此字段的值设置为
true。
请注意,使用 CMP 时,无需手动启用受限广告。
- 示例
JavaScript
// Manually enable limited ads serving. // GPT must be loaded from the limited ads URL to configure this setting. googletag.pubads().setPrivacySettings({ limitedAds: true, });
JavaScript(旧版)
// Manually enable limited ads serving. // GPT must be loaded from the limited ads URL to configure this setting. googletag.pubads().setPrivacySettings({ limitedAds: true, });
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?: booleanOptional restrictDataProcessing
restrictDataProcessing?: booleanOptional 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?: TrafficSourceundefined。- 示例
JavaScript
// Indicate requests represent organic traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.ORGANIC, }); // Indicate requests represent purchased traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.PURCHASED, });
JavaScript(旧版)
// Indicate requests represent organic traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.ORGANIC, }); // Indicate requests represent purchased traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.PURCHASED, });
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
googletag.PubAdsService
扩展
ServicePublisher Ads 服务。此服务用于从您的 Google Ad Manager 账号中提取并展示广告。
| 方法 | |
|---|---|
add | 注册一个监听器,以便您在网页上发生特定 GPT 事件时设置并调用 JavaScript 函数。 继承自 |
clear | 从给定广告位中移除广告,并将其替换为空白内容。 |
clear | 已弃用。 清除所有网页级广告类别排除标签。 |
clear | 已弃用。 清除特定键或所有键的自定义定位参数。 |
collapse | 已弃用。 启用“合拢广告位 div”功能,以便在没有要显示的广告内容时,这些 div 不会占用网页上的任何空间。 |
disable | 已弃用。 禁止在网页加载时请求广告,但允许通过 PubAdsService.refresh 调用来请求广告。 |
display | 使用指定广告单元路径和尺寸构建并展示广告位。 |
enable | 已弃用。 在 GPT 中启用延迟加载(由配置对象定义)。 |
enable | 已弃用。 启用单一请求模式,以便同时提取多个广告。 |
enable | 已弃用。 向 GPT 发出信号,表明网页上将展示视频广告。 |
get | 已弃用。 返回与给定键关联的 AdSense 属性的值。 |
get | 已弃用。 返回已在此服务上设置的属性键。 |
get | 获取与此服务关联的时段列表。 继承自 |
get | 已弃用。 返回已设置的特定自定义服务级定位参数。 |
get | 已弃用。 返回已设置的所有自定义服务级定位键的列表。 |
is | 已弃用。 返回之前的 PubAdsService.disableInitialLoad 调用是否成功停用了初始广告请求。 |
refresh | 为网页上的特定广告位或所有广告位提取并展示新广告。 |
register | 注册一个钩子,以便在全局超时时间内,在页面上的每个广告请求之前与其他已注册的钩子并行执行。 |
remove | 移除之前注册的监听器。 继承自 |
set | 已弃用。 为适用于发布商广告服务下所有广告位的 AdSense 属性设置值。 |
set | 已弃用。 为指定标签名称设置网页级广告类别排除。 |
set | 已弃用。 启用和停用广告水平居中。 |
set | 已弃用。 配置是否应强制网页上的所有广告都使用 SafeFrame 容器呈现。 |
set | 已弃用。 传递网站中的位置信息,以便您将订单项定位到特定地理位置。 |
set | 允许使用配置对象通过单个 API 配置所有隐私设置。 |
set | 为发布商提供的 ID 设置值。 |
set | 已弃用。 设置 SafeFrame 配置的页面级偏好设置。 |
set | 已弃用。 为给定键设置适用于所有发布商广告服务广告位的自定义定位参数。 |
set | 已弃用。 设置要随广告请求一起发送的视频内容信息,以便进行定位和内容排除。 |
update | 更改随广告请求发送的相关因子,从而有效启动新的网页浏览。 |
方法
clear
clear(slots?: Slot[]): boolean从给定广告位中移除广告,并将其替换为空白内容。这些广告位将被标记为未提取。
具体而言,清空广告位会从 GPT 的长效网页浏览中移除广告,因此未来的请求不会受到涉及此广告的包版或竞争性排除的影响。
具体而言,清空广告位会从 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();
| 参数 | |
|---|---|
| 要清除的槽位数组。数组是可选的;如果未指定,则所有槽都将被清除。 |
| 返回 | |
|---|---|
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.
- 另请参阅
| 参数 | |
|---|---|
| 定位参数键。该键是可选的;如果未指定,所有定位参数都将被清除。 |
| 返回 | |
|---|---|
PubAdsService | 调用该方法的服务对象。 |
collapseEmptyDivs
collapseEmptyDivs(collapseBeforeAdFetch?: boolean): booleandisableInitialLoad
disableInitialLoad(): void停用在网页加载时发出的广告请求,但允许通过 PubAdsService.refresh 调用来请求广告。此设置应在启用服务之前完成。必须使用异步模式;否则将无法使用
refresh 请求广告。- 另请参阅
display
display(adUnitPath: string, size: GeneralSize, div?: string | Element, clickUrl?: string): void使用给定的广告单元路径和尺寸构建并展示广告位。
此方法是先调用 googletag.defineSlot,然后立即调用 googletag.display 的简写形式。
此方法的行为取决于是否启用了单一请求架构 (SRA):
此方法是先调用 googletag.defineSlot,然后立即调用 googletag.display 的简写形式。
此方法的行为取决于是否启用了单一请求架构 (SRA):
- 已启用 SRA:截至此次调用时定义的所有广告位都将进行批处理并一起请求。
- SRA 已停用(默认):广告位将单独请求。
display() 或 refresh() 请求。- 示例
JavaScript
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
JavaScript(旧版)
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
TypeScript
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
| 参数 | |
|---|---|
adUnitPath: string | 要呈现的广告位的广告单元路径。 |
size: GeneralSize | 广告位的宽度和高度。 |
| 包含广告位的 div 的 ID 或 div 元素本身。 |
| 要在此广告位上使用的点击跟踪网址。 |
enableLazyLoad
enableLazyLoad(config?: {
fetchMarginPercent?: number;
mobileScaling?: number;
renderMarginPercent?: number;
}): void在 GPT 中启用延迟加载(由配置对象定义)。如需查看更详细的示例,请参阅延迟加载示例。
注意:只有当所有广告位都位于提取边距之外时,SRA 中的延迟提取才会起作用。
注意:只有当所有广告位都位于提取边距之外时,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, }, });
- 另请参阅
| 参数 | |
|---|---|
| 配置对象允许自定义延迟行为。任何省略的配置都将使用 Google 设置的默认值,这些默认值会随着时间的推移而调整。如需停用特定设置(例如提取边距),请将值设置为 -1。
|
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为网页上的特定广告位或所有广告位提取并展示新广告。仅在异步呈现模式下有效。
为了在所有浏览器中都能正常运行,必须先调用
刷新广告位会从 GPT 的长期页面浏览中移除旧广告,因此未来的请求不会受到涉及该广告的包揽式广告或竞争性排除的影响。
为了在所有浏览器中都能正常运行,必须先调用
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 });
| 参数 | |
|---|---|
| 要刷新的广告位。数组是可选的;如果未指定,则所有广告位都会刷新。 |
| 与此刷新调用关联的配置选项。
|
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: boolean | true 表示广告居中,false 表示广告左对齐。 |
setForceSafeFrame
setForceSafeFrame(forceSafeFrame: boolean): PubAdsService配置是否应强制使用 SafeFrame 容器呈现网页上的所有广告。
使用此 API 时,请注意以下事项:
使用此 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: boolean | true,强制在 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 的长效网页浏览量没有影响,后者会自动反映网页上实际展示的广告,并且没有过期时间。
注意:这对 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
表示单个广告响应的对象。
| 属性 | |
|---|---|
advertiser | 广告客户的 ID。 |
campaign | 广告系列的 ID。 |
creative | 广告素材的 ID。 |
creative | 广告的模板 ID。 |
line | 订单项的 ID。 |
属性
advertiserId
advertiserId: numbercampaignId
campaignId: numbercreativeId
creativeId: numbercreativeTemplateId
creativeTemplateId: numberlineItemId
lineItemId: numbergoogletag.RewardedPayload
一个表示与激励广告相关联的奖励的对象
| 属性 | |
|---|---|
amount | 奖励中包含的物品数量。 |
type | 奖励中包含的物品类型(例如“金币”)。 |
- 另请参阅
属性
amount
amount: numbertype
type: stringgoogletag.Service
包含所有服务通用方法的基础服务类。
| 方法 | |
|---|---|
add | 注册一个监听器,以便您在网页上发生特定 GPT 事件时设置并调用 JavaScript 函数。 |
get | 获取与此服务关联的时段列表。 |
remove | 移除之前注册的监听器。 |
方法
addEventListener
addEventListener<K extends keyof EventTypeMap>(eventType: K, listener: ((arg: EventTypeMap[K]) => void)): Service注册一个监听器,以便在网页上发生特定 GPT 事件时设置并调用 JavaScript 函数。支持以下事件:
- events.GameManualInterstitialSlotClosedEvent
- events.GameManualInterstitialSlotReadyEvent
- events.ImpressionViewableEvent
- events.RewardedSlotClosedEvent
- events.RewardedSlotGrantedEvent
- events.RewardedSlotReadyEvent
- events.SlotOnloadEvent
- events.SlotRenderEndedEvent
- events.SlotRequestedEvent
- events.SlotResponseReceived
- events.SlotVisibilityChangedEvent
- 示例
JavaScript
// 1. Adding an event listener for the PubAdsService. googletag.pubads().addEventListener("slotOnload", (event) => { console.log("Slot has been loaded:"); console.log(event); }); // 2. Adding an event listener with slot specific logic. // Listeners operate at service level, which means that you cannot add // a listener for an event for a specific slot only. You can, however, // programmatically filter a listener to respond only to a certain ad // slot, using this pattern: const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", (event) => { if (event.slot === targetSlot) { // Slot specific logic. } });
JavaScript(旧版)
// 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
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
尺寸映射规范对象的构建器。此构建器旨在帮助您轻松构建尺寸规范。
| 方法 | |
|---|---|
add | 添加从单尺寸数组(表示视口)到单尺寸或多尺寸数组(表示广告位)的映射。 |
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 < 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 < 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 < 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 是一个对象,代表网页上的单个广告位。
| 方法 | |
|---|---|
add | 向此槽添加 Service。 |
clear | 已弃用。 清除此广告位的所有广告位级广告类别排除标签。 |
clear | 已弃用。 清除此广告位的特定或所有自定义广告位级定位参数。 |
define | 为此广告位设置从最小视口尺寸到广告位尺寸的映射数组。 |
get | 已弃用。 返回与此广告位的给定键关联的 AdSense 属性的值。 |
get | 返回广告单元的完整路径,其中包含广告资源网代码和广告单元路径。 |
get | 已弃用。 返回在此广告位上设置的属性键列表。 |
get | 已弃用。 返回此广告位的广告类别排除标签。 |
get | 获取由 setConfig 设置的广告位的常规配置选项的冻结副本。 |
get | 返回广告响应信息。 |
get | 返回定义槽位时提供的槽位 div 的 ID。 |
get | 已弃用。 返回在此广告位上设置的特定自定义定位参数。 |
get | 已弃用。 返回在此广告位上设置的所有自定义定位键的列表。 |
set | 已弃用。 为此广告位上的 AdSense 属性设置值。 |
set | 已弃用。 在此广告位上设置广告位级广告类别排除标签。 |
set | 已弃用。 设置用户点击广告后将被重定向到的点击跟踪网址。 |
set | 已弃用。 设置当广告位 div 中没有广告时是否应隐藏该广告位。 |
set | 为此广告位设置常规配置选项。 |
set | 已弃用。 配置是否应强制使用 SafeFrame 容器呈现此广告位中的广告。 |
set | 已弃用。 设置 SafeFrame 配置的广告位级偏好设置。 |
set | 已弃用。 为此广告位设置自定义定位参数。 |
update | 已弃用。 通过 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.
- 另请参阅
| 参数 | |
|---|---|
| 定位参数键。该键是可选的;如果未指定,所有定位参数都将被清除。 |
| 返回 | |
|---|---|
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 请求。
即使点击跟踪网址被替换,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 | 是否在未返回广告时收缩广告位。 |
| 是否在提取广告之前就收缩广告位。如果 collapse 不是 true,则会被忽略。 |
| 返回 | |
|---|---|
Slot | 调用该方法的广告位对象。 |
setConfig
setConfig(slotConfig: SlotSettingsConfig): Slot为此广告位设置常规配置选项。
| 参数 | |
|---|---|
slotConfig: SlotSettingsConfig | 配置对象。 |
| 返回 | |
|---|---|
Slot | 调用该方法的广告位对象。 |
setForceSafeFrame
setForceSafeFrame(forceSafeFrame: boolean): Slot配置是否应强制使用 SafeFrame 容器呈现此广告位中的广告。
使用此 API 时,请注意以下几点:
使用此 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: boolean | true:强制此广告位中的所有广告在 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: { | 定位参数键值对映射。 |
| 返回 | |
|---|---|
Slot | 调用该方法的广告位对象。 |
googletag.config
页面级设置的主配置界面。
| 接口 | |
|---|---|
Ad | 用于控制广告展开的设置。 |
Ad | 用于控制 AdSense 广告行为的设置。 |
Auto | 自动刷新配置设置。 |
Continue | 用于配置“继续”按钮行为的设置。 |
Interstitial | 一个对象,用于定义单个插页式广告位的行为。 |
Lazy | 用于控制在 GPT 中使用延迟加载的设置。 |
Page | 页面级设置的主配置界面。 |
Privacy | 用于控制发布商隐私权处理方式的设置。 |
Publisher | 发布商提供的信号 (PPS) 配置对象。 |
Safe | 用于控制 GPT 中的 SafeFrame 的设置。 |
Slot | 用于广告位级设置的主配置界面。 |
Taxonomy | 一个包含单个类目的值的对象。 |
Video | 用于配置视频广告相关设置的设置。 |
| 类型别名 | |
|---|---|
Collapse | 用于控制广告位收起行为的支持值。 |
Interstitial | 支持的插页式广告触发器。 |
Privacy | 支持的发布商隐私保护处理措施。 |
Taxonomy | 发布商提供的信号 (PPS) 支持的类目。 |
类型别名
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"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 已启用
googletag.config.AdSenseAttributesConfig
用于控制 AdSense 广告行为的设置。
这些属性可用于针对每个请求覆盖服务器端设置。
这些属性可用于针对每个请求覆盖服务器端设置。
| 属性 | |
|---|---|
adsense | AdSense 广告格式。 |
adsense | AdSense 渠道 ID。 |
adsense | 是否已启用测试模式。 |
document | 展示广告的网页所用的语言。 |
page | 展示广告的网页的网址。 |
属性
Optional adsense_ad_format
adsense_ad_format?: "120x240_as" | "120x600_as" | "125x125_as" | "160x600_as" | "180x150_as" | "200x200_as" | "234x60_as" | "250x250_as" | "300x250_as" | "336x280_as" | "468x60_as" | "728x90_as"Optional adsense_channel_ids
adsense_channel_ids?: string允许的值为以“+”分隔的渠道 ID。
示例:
271828183+314159265- 另请参阅
Optional adsense_test_mode
adsense_test_mode?: "on"如果设置为
on,广告会被标记为仅供测试,不会纳入统计或结算。对于生产环境中的非测试流量,必须取消设置此设置。Optional document_language
Optional page_url
page_url?: string允许的值为有效网址。
示例:
http://www.example.comgoogletag.config.AutoRefreshConfig
自动刷新配置设置。
| 属性 | |
|---|---|
back | 当网页从往返缓存中恢复时,GPT 是否会自动刷新正在被浏览的广告位。 |
heavy | 如果 Chrome 的重度广告干预机制在广告 iframe 上触发,GPT 是否会自动刷新广告位。 |
属性
Optional backForwardCache
backForwardCache?: booleantrue。- 示例
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?: booleantrue。- 示例
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
用于配置“继续”按钮行为的设置。
| 属性 | |
|---|---|
background | 按钮的背景颜色。 |
font | 按钮文字的字体系列。 |
font | 按钮的文字颜色。 |
freq | 频次上限间隔时间(以分钟为单位)。 |
target | 要在其上呈现/触发“继续”按钮的 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?: stringgoogletag.config.InterstitialConfig
一个对象,用于定义单个插页式广告位的行为。
| 属性 | |
|---|---|
require | 是否需要征得用户同意才能使用本地存储空间来展示此插页式广告。 |
triggers | 此插页式广告的插页式广告触发器配置。 |
属性
Optional requireStorageAccess
requireStorageAccess?: booleanGPT 会使用本地存储空间来强制执行插页式广告的频次上限。不过,未同意使用本地存储空间的用户仍有资格看到插页式广告。将此属性设置为
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 中使用延迟加载的设置。
| 属性 | |
|---|---|
fetch | 广告位与当前视口之间的最小距离(以视口大小的百分比表示),达到此距离后,我们才会请求广告。 |
mobile | 应用于移动设备上边距的系数。 |
render | 广告位与当前视口之间的最小距离(以视口大小的百分比表示),达到此距离后,我们才会呈现广告。 |
属性
Optional fetchMarginPercent
fetchMarginPercent?: number此设置与 renderMarginPercent 结合使用,可让您预提取广告,但等待呈现和下载其他子资源。因此,此值应始终大于或等于 renderMarginPercent。
值为
0 表示“当广告位进入视口时”,值为 100 表示“当广告距离视口 1 个视口高度时”,以此类推。Optional mobileScaling
mobileScaling?: number这样,您就可以在移动设备和桌面设备上设置不同的边距,因为两者的视口大小和滚动速度可能不同。例如,如果值为 2.0,则移动设备上的所有边距都会乘以 2,从而增加广告位在提取和呈现之前与视口之间的最小距离。
Optional renderMarginPercent
renderMarginPercent?: number此设置与 fetchMarginPercent 结合使用,可让您预提取广告,但等待呈现和下载其他子资源。因此,此值应始终小于或等于 fetchMarginPercent。
值为
0 表示“当广告位进入视口时”,值为 100 表示“当广告距离视口 1 个视口时”,以此类推。googletag.config.PageSettingsConfig
用于进行网页级设置的主配置接口。
允许通过单个 API 调用设置多项功能。
下面列出的所有属性均为示例,并不反映利用 setConfig 的实际功能。如需了解功能集,请参阅下文 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, });
| 属性 | |
|---|---|
ad | 用于控制广告展开的设置。 |
adsense | 用于配置 AdSense 属性的设置。 |
ad | 已弃用。 |
auto | 用于配置自动广告刷新行为的设置。 |
category | 用于配置广告类别排除对象的设置。 |
centering | 用于控制广告水平居中的设置。 |
collapse | 用于控制广告位收起行为的设置。 |
disable | 用于控制何时请求广告的设置。 |
lazy | 用于控制在 GPT 中使用延迟加载的设置。 |
location | 用于将订单项地理位置定位到地理位置的设置。 |
pps | 用于控制发布商提供的信号 (PPS) 的设置。 |
privacy | 用于控制发布商隐私权处理方式的设置。 |
request | 此设置用于控制 GPT 在继续发出广告请求之前,等待所有已注册的请求钩子完成的最长时间。 |
safe | 用于控制在 GPT 中使用 SafeFrame 的设置。 |
single | 用于启用或停用单一请求架构 (SRA) 的设置。 |
targeting | 用于控制键值对定位的设置。 |
thread | 用于控制 GPT 在请求和呈现广告素材时是否应让出 JS 线程的设置。 |
video | 用于控制视频广告的设置。 |
属性
Optional adExpansion
adExpansion?: AdExpansionConfigOptional adsenseAttributes
adsenseAttributes?: AdSenseAttributesConfig通过此设置配置的 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延迟加载是一种延迟请求和呈现广告的技术,直到广告接近用户的视口。如需查看更详细的示例,请参阅延迟加载示例。
注意:如果启用了
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?: PrivacyTreatmentsConfigOptional Experimental requestHookTimeoutMs
requestHookTimeoutMs?: number | "auto"所有已注册的请求钩子都会并行执行。此超时时间定义了广告请求流程在等待这些并行执行完成时将暂停的时长上限。
支持的值:
- 正数(以毫秒为单位):自定义等待期。
'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通过此设置配置的值将应用于网页上的所有广告位。各个广告位可以通过 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 后,在调用 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 仅会为支持 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>>googletag.config.SafeFrameConfig
用于控制 GPT 中的 SafeFrame 的设置。
| 属性 | |
|---|---|
allow | SafeFrame 是否应允许广告内容通过覆盖网页内容来展开。 |
allow | SafeFrame 是否应允许广告内容通过推送网页内容来展开。 |
force | 是否应强制使用 SafeFrame 容器呈现广告。 |
sandbox | SafeFrame 是否应使用 HTML5 sandbox 属性来阻止在没有用户互动的情况下进行顶层导航。 |
use | 已弃用。 SafeFrame 是否应针对预订型广告素材使用随机子网域。 |
属性
Optional allowOverlayExpansion
allowOverlayExpansion?: booleanOptional allowPushExpansion
allowPushExpansion?: booleanOptional forceSafeFrame
forceSafeFrame?: booleanOptional 沙盒
sandbox?: booleantrue(无法强制设为 false)。请注意,沙盒属性会停用插件(例如 Flash)。Optional useUniqueDomain
useUniqueDomain?: booleannull 可清除存储的值。注意:此功能默认处于启用状态。
googletag.config.SlotSettingsConfig
用于插槽级设置的主配置接口。
允许通过单个 API 调用为单个插槽设置多项功能。
下面列出的所有属性均为示例,并不反映利用 setConfig 的实际功能。如需了解功能集,请参阅下文 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, });
| 属性 | |
|---|---|
ad | 用于配置广告展开功能的设置。 |
adsense | 用于配置 AdSense 属性的设置。 |
category | 用于配置广告类别排除对象的设置。 |
click | 用于配置用户点击广告后将被重定向到的网址的设置。 |
collapse | 用于配置广告位收起行为的设置。 |
continue | 用于配置内容暂停时广告的“继续”按钮行为的设置。 |
interstitial | 用于配置插页式广告位行为的设置。 |
safe | 用于在 GPT 中配置 SafeFrame 使用情况的设置。 |
targeting | 用于配置键值对定位的设置。 |
属性
Optional adExpansion
adExpansion?: AdExpansionConfig- 另请参阅
Optional adsenseAttributes
adsenseAttributes?: AdSenseAttributesConfig通过此设置配置的 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通过此设置配置的值将仅应用于广告位,并会覆盖通过 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[]googletag.config.VideoAdsConfig
用于配置视频广告相关设置的设置。
| 属性 | |
|---|---|
enable | 网页上是否会展示视频广告。 |
video | 视频内容来源 ID。 |
video | 视频内容 ID。 |
属性
enableVideoAds
enableVideoAds: boolean如果设置为
true,则会针对展示广告和视频广告启用内容排除限制。如果视频内容已知,请将 videoContentId 和 videoCmsId 设置为提供给 Google Ad Manager 内容提取服务的值,以便对展示广告使用内容排除功能。
Optional videoCmsId
Optional videoContentId
googletag.enums
这是 GPT 用于枚举类型的命名空间。
| 枚举 | |
|---|---|
Out | GPT 支持的页外广告格式。 |
Tag | GPT 支持的年龄处理方式设置。 |
Traffic | GPT 支持的流量来源。 |
枚举
OutOfPageFormat
TagForAgeTreatment
TrafficSource
googletag.events
这是 GPT 用于事件的命名空间。您的代码可以使用 Service.addEventListener 响应这些事件。
| 接口 | |
|---|---|
Event | 所有 GPT 事件的基本接口。 |
Event | 这是一种伪类型,用于将事件名称映射到其对应的事件对象类型,以便 Service.addEventListener 和 Service.removeEventListener 使用。 |
Game | 当用户关闭游戏手动插页式广告位时,系统会触发此事件。 |
Game | 当游戏手动插页式广告位已准备好向用户展示时,系统会触发此事件。 |
Impression | 当展示根据 Active View 条件变为可见时,系统会触发此事件。 |
Rewarded | 当用户关闭激励广告位时,系统会触发此事件。 |
Rewarded | 当用户因观看激励广告而获得奖励时,系统会触发此事件。 |
Rewarded | 此事件会在激励广告准备好展示时触发。 |
Rewarded | 此事件会在激励视频广告播放完毕时触发。 |
Slot | 当广告素材的 iframe 触发其加载事件时,系统会触发此事件。 |
Slot | 当广告素材代码注入到广告位中时,系统会触发此事件。 |
Slot | 当系统为特定广告位请求广告时,会触发此事件。 |
Slot | 当特定广告位收到广告响应时,系统会触发此事件。 |
Slot | 每当广告位区域在屏幕上所占的百分比发生变化时,就会触发此事件。 |
googletag.events.Event
所有 GPT 事件的基础接口。以下所有 GPT 事件都将包含以下字段。
| 属性 | |
|---|---|
service | 触发事件的服务的名称。 |
slot | 触发事件的槽。 |
- 另请参阅
属性
serviceName
serviceName: stringslot
slot: Slotgoogletag.events.EventTypeMap
这是一种伪类型,用于将事件名称映射到其对应的事件对象类型,以便 Service.addEventListener 和 Service.removeEventListener 使用。记录此类型仅供参考,并用于确保类型安全。
属性
gameManualInterstitialSlotClosed
gameManualInterstitialSlotClosed: GameManualInterstitialSlotClosedEventgameManualInterstitialSlotReady
gameManualInterstitialSlotReady: GameManualInterstitialSlotReadyEventimpressionViewable
impressionViewable: ImpressionViewableEventrewardedSlotClosed
rewardedSlotClosed: RewardedSlotClosedEventrewardedSlotGranted
rewardedSlotGranted: RewardedSlotGrantedEventrewardedSlotReady
rewardedSlotReady: RewardedSlotReadyEventrewardedSlotVideoCompleted
rewardedSlotVideoCompleted: RewardedSlotVideoCompletedEventslotOnload
slotOnload: SlotOnloadEventslotRenderEnded
slotRenderEnded: SlotRenderEndedEventslotRequested
slotRequested: SlotRequestedEventslotResponseReceived
slotResponseReceived: SlotResponseReceivedslotVisibilityChanged
slotVisibilityChanged: SlotVisibilityChangedEventgoogletag.events.GameManualInterstitialSlotClosedEvent
扩展
Event| 属性 | |
|---|---|
service | 触发事件的服务的名称。 继承自 |
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| 属性 | |
|---|---|
service | 触发事件的服务的名称。 继承自 |
slot | 触发事件的槽。 继承自 |
| 方法 | |
|---|---|
make | 向用户展示游戏手动插页式广告。 |
- 示例
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 条件变为可见时,系统会触发此事件。
| 属性 | |
|---|---|
service | 触发事件的服务的名称。 继承自 |
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。
| 属性 | |
|---|---|
service | 触发事件的服务的名称。 继承自 |
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 | 一个包含所获奖励相关信息的对象。 |
service | 触发事件的服务的名称。 继承自 |
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. } }); }
属性
载荷
payload: RewardedPayloadgoogletag.events.RewardedSlotReadyEvent
扩展
Event当激励广告准备好展示时,系统会触发此事件。发布商负责在展示广告之前向用户提供观看广告的选项。
| 属性 | |
|---|---|
service | 触发事件的服务的名称。 继承自 |
slot | 触发事件的槽。 继承自 |
| 方法 | |
|---|---|
make | 展示激励广告。 |
- 示例
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此事件会在激励视频广告播放完毕时触发。
| 属性 | |
|---|---|
service | 触发事件的服务的名称。 继承自 |
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。| 属性 | |
|---|---|
service | 触发事件的服务的名称。 继承自 |
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。
| 属性 | |
|---|---|
advertiser | 所呈现广告的广告客户 ID。 |
campaign | 所呈现广告的广告系列 ID。 |
company | 对已呈现的补余广告出价的公司的 ID。 |
creative | 所呈现的预订型广告的广告素材 ID。 |
creative | 所呈现预订型广告的广告素材模板 ID。 |
is | 广告是否为补余广告。 |
is | 是否为广告位返回了广告。 |
label | 已弃用。 |
line | 所呈现预订型广告的订单项 ID。 |
response | 响应标识符是广告响应的唯一标识符。 |
service | 触发事件的服务的名称。 继承自 |
size | 表示所呈现广告素材的像素尺寸。 |
slot | 触发事件的槽。 继承自 |
slot | 插槽内容是否已随呈现的广告而更改。 |
source | 所呈现的预订型广告或补余广告的广告素材 ID。 |
source | 所呈现的预订广告或补余广告的订单项 ID。 |
yield | 所呈现补余广告的收益组 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
campaignId
companyIds
creativeId
creativeTemplateId
isBackfill
isBackfill: booleantrue,否则为 false。isEmpty
isEmpty: booleantrue,否则为 false。labelIds
labelIds: number[]lineItemId
responseIdentifier
responseIdentifier: stringsize
size: string | number[][728, 90]。对于空广告位,此值为 null。slotContentChanged
slotContentChanged: booleantrue,否则为 false。sourceAgnosticCreativeId
sourceAgnosticCreativeId: numbernull。sourceAgnosticLineItemId
sourceAgnosticLineItemId: numbernull。yieldGroupIds
googletag.events.SlotRequestedEvent
扩展
Event当系统为特定广告位请求广告时,会触发此事件。
| 属性 | |
|---|---|
service | 触发事件的服务的名称。 继承自 |
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当特定广告位收到广告响应时,系统会触发此事件。
| 属性 | |
|---|---|
service | 触发事件的服务的名称。 继承自 |
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 毫秒一次。
| 属性 | |
|---|---|
in | 广告可见区域所占的百分比。 |
service | 触发事件的服务的名称。 继承自 |
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: numbergoogletag.secureSignals
这是 GPT 用于管理安全信号的命名空间。
| 接口 | |
|---|---|
Bidder | 返回特定出价方的安全信号。 |
Publisher | 返回特定发布商的安全信号。 |
Secure | 用于管理安全信号的界面。 |
| 类型别名 | |
|---|---|
Secure | 用于为特定出价方或提供商返回安全信号的接口。 |
类型别名
SecureSignalProvider
SecureSignalProvider: BidderSignalProvider | PublisherSignalProviderid 或 networkCode,但不能同时提供这两者。googletag.secureSignals.BidderSignalProvider
返回特定出价方的安全信号。
出价方安全信号提供程序由 2 部分组成:
出价方安全信号提供程序由 2 部分组成:
- 一个收集器函数,该函数会返回一个解析为安全信号的
Promise。 - 一个
id,用于标识与信号关联的出价方。
| 属性 | |
|---|---|
collector | 一个函数,用于返回一个可解析为安全信号的 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: stringgoogletag.secureSignals.PublisherSignalProvider
返回特定发布商的安全信号。
发布商信号提供商由 2 部分组成:
发布商信号提供商由 2 部分组成:
- 一个收集器函数,该函数会返回一个
Promise,其解析结果为安全信号。 - 一个
networkCode,用于标识与信号关联的发布商。
| 属性 | |
|---|---|
collector | 一个函数,用于返回一个可解析为安全信号的 Promise。 |
network | 与此安全信号关联的发布商的网络代码(如广告单元路径中所示)。 |
- 示例
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: stringgoogletag.secureSignals.SecureSignalProvidersArray
用于管理安全信号的界面。
| 方法 | |
|---|---|
clear | 从缓存中清除所有收集器的所有信号。 |
push | 向信号提供商数组添加新的 secureSignals.SecureSignalProvider,并开始信号生成流程。 |
方法
clearAllCache
clearAllCache(): void从缓存中清除所有收集器的所有信号。
调用此方法可能会降低在当前和潜在的后续网页浏览中,信号被纳入广告请求的可能性。因此,只有在发生有意义的状态更改(例如,发生表明有新用户的事件,如登录、退出、注册等)时,才应调用此方法。
调用此方法可能会降低在当前和潜在的后续网页浏览中,信号被纳入广告请求的可能性。因此,只有在发生有意义的状态更改(例如,发生表明有新用户的事件,如登录、退出、注册等)时,才应调用此方法。
push
push(provider: SecureSignalProvider): void向信号提供商数组添加新的 secureSignals.SecureSignalProvider,并开始信号生成流程。
| 参数 | |
|---|---|
provider: SecureSignalProvider | 要添加到数组中的 secureSignals.SecureSignalProvider 对象。 |