GPT 参考文档

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

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

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

类型注解

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

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


类型定义

类型
SingleSize | MultiSize

广告位的有效尺寸配置,可以是一个或多个尺寸。

SingleSize[]

单个有效尺寸的列表。

"fluid" | ["fluid"]

广告位可以采用的已命名尺寸。在大多数情况下,尺寸是固定尺寸的矩形,但在某些情况下,我们需要其他种类的尺寸规范。只有以下尺寸是有效的命名尺寸:

  • fluid:广告容器占据父 div 宽度的 100%,并会调整其高度以适应广告素材内容。与网页上常规 block 元素的行为类似。用于原生广告(请参阅相关文章)。请注意,fluid['fluid'] 都可用于将槽大小声明为自适应尺寸。

SingleSizeArray | NamedSize

槽的单个有效尺寸。

[number, number]

由代表 [宽度, 高度] 的两个数字组成的数组。

[SingleSizeArray, GeneralSize]

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

SizeMapping[]

尺寸映射列表。

"unhideWindow" | "navBar"

受支持的插页式广告触发器。

"disablePersonalization"

支持的发布商隐私权处理方式。

"IAB_AUDIENCE_1_1" | "IAB_CONTENT_2_2"

支持的发布商提供的信号 (PPS) 类目。

BidderSignalProvider | PublisherSignalProvider

用于为特定出价方或提供商返回安全信号的界面。必须提供 idnetworkCode 中的一个,但不能同时提供两者。

枚举类型

枚举
googletag.enums.OutOfPageFormat
GPT 支持的页外格式。
googletag.enums.TrafficSource
GPT 支持的流量来源


googletag.enums.OutOfPageFormat

  • GPT 支持的页外格式。

  • 另请参阅
  • BOTTOM_ANCHOR
    广告位固定在视口底部的锚点格式。
    INTERSTITIAL
    网站插页式广告素材格式。
    LEFT_SIDE_RAIL
    左侧边栏广告格式。
    REWARDED
    激励广告格式。
    RIGHT_SIDE_RAIL
    采用右侧边栏格式。
    TOP_ANCHOR
    广告位固定在视口顶部的锚点格式。


googletag.enums.TrafficSource

  • GPT 支持的流量来源

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


googletag

Google 发布商代码用于其 API 的全局命名空间。

变量摘要
apiReady
此标记指示 GPT API 已加载并准备好调用。
cmd
引用全局命令队列,以异步执行 GPT 相关调用。
pubadsReady
此标记指示 PubAdsService 已启用、已加载并完全正常运行。
secureSignalProviders
对安全信号提供程序数组的引用。
函数摘要
companionAds
返回对 CompanionAdsService 的引用。
defineOutOfPageSlot
使用指定广告单元路径构建一个页外广告位。
defineSlot
使用指定广告单元路径和尺寸构建一个广告位,并将其与网页上将包含广告的 div 元素的 ID 相关联。
destroySlots
销毁指定的广告位,同时从 GPT 中移除这些广告位的所有相关对象和引用。
disablePublisherConsole
停用 Google 发布商控制台。
display
指示槽服务渲染槽。
enableServices
启用已针对网页上的广告位定义的所有 GPT 服务。
getVersion
返回 GPT 的当前版本。
openConsole
打开 Google 发布商控制台。
pubads
返回对 PubAdsService 的引用。
setAdIframeTitle
从现在开始,为 PubAdsService 创建的所有广告容器 iframe 设置标题。
setConfig
设置页面的常规配置选项。
sizeMapping
创建一个新的 SizeMappingBuilder


googletagapiReady

  • apiReady: boolean | undefined
  • 此标记指示 GPT API 已加载并准备好调用。在 API 准备就绪之前,此属性将直接为 undefined

    请注意,处理异步请求的方法是使用 googletag.cmd 将回调函数加入队列,待 GPT 准备就绪时再进行调用。这些回调不需要检查 googletag.apiReady,因为它们在设置 API 后一定会执行。

  • 示例

    JavaScript

    if (window.googletag && googletag.apiReady) {
      // GPT API can be called safely.
    }
    

    JavaScript(旧版)

    if (window.googletag && googletag.apiReady) {
      // GPT API can be called safely.
    }
    

    TypeScript

    if (window.googletag && googletag.apiReady) {
      // GPT API can be called safely.
    }
    


googletagcmd

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

    网页上的 GPT 代码语法会将 googletag.cmd 变量初始化为一个空的 JavaScript 数组,而 cmd.push 是向数组末尾添加元素的标准 Array.push 方法。当 GPT JavaScript 加载完毕后,它会遍历数组并按顺序执行所有函数。然后,脚本会将 cmd 替换为 CommandArray 对象,该对象定义了 push 方法以执行传递给它的函数参数。这种机制在异步提取 JavaScript 的同时允许浏览器继续呈现网页,从而使 GPT 可以减少用户感知的延迟时间。

  • 示例

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


googletagpubadsReady

  • pubadsReady: boolean | undefined
  • 此标记指示 PubAdsService 已启用、已加载并完全正常运行。在调用 enableServices 以及加载并初始化 PubAdsService 之前,此属性直接为 undefined


googletagsecureSignalProviders

  • 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");
      },
    });
    
    另请参阅


googletagcompanionAds


googletagdefineOutOfPageSlot

  • defineOutOfPageSlot(adUnitPath: string, div?: string | OutOfPageFormat): Slot | null
  • 使用指定广告单元路径构建一个页外广告位。

    对于自定义页外广告,div 是包含广告的 div 元素的 ID。如需了解更多详情,请参阅关于页外广告素材的文章。

    对于由 GPT 管理的页外广告,div 是受支持的 OutOfPageFormat 格式。

  • 示例

    JavaScript

    // Define a custom out-of-page ad slot.
    googletag.defineOutOfPageSlot("/1234567/sports", "div-1");
    
    // Define a GPT managed web interstitial ad slot.
    googletag.defineOutOfPageSlot("/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL);
    

    JavaScript(旧版)

    // Define a custom out-of-page ad slot.
    googletag.defineOutOfPageSlot("/1234567/sports", "div-1");
    
    // Define a GPT managed web interstitial ad slot.
    googletag.defineOutOfPageSlot("/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL);
    

    TypeScript

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


googletagdefineSlot

  • 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?: string
    将包含此广告单元的 div 的 ID。
  • 返回
    Slot | null
    新创建的槽位,或 null(如果无法创建槽位)。


googletagdestroySlots

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

    针对某个广告位调用此 API 会清除广告并将广告位对象从 GPT 维护的内部状态中移除。对 slot 对象调用任何其他函数将会导致出现未定义的行为。请注意,如果发布商网页保留了对该广告位的引用,则浏览器仍可能无法释放与该广告位相关联的内存。调用此 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();
    
  • 参数
    slots?: Slot[]
    要销毁的槽数组。数组是可选的;如果未指定,所有槽都将被销毁。
  • 返回
    boolean
    如果槽已销毁,则为 true,否则为 false


googletagdisablePublisherConsole


googletagdisplay

  • display(divOrSlot: string | Element | Slot): void
  • 指示槽服务渲染槽。对于每个网页,每个广告位只能显示一次。所有广告位都必须进行定义并与某个服务相关联,然后才能进行显示。除非该元素出现在 DOM 中,否则不得执行 display 调用。若要实现此目的,通常可以将其放在方法调用中指定的 div 元素中的脚本块中。

    如果使用单一请求架构 (SRA),系统会在调用此方法时一次性提取所有未提取的广告位。要强制广告位不显示,必须移除整个 div。

  • 示例

    JavaScript

    googletag.cmd.push(() => {
      googletag.display("div-1");
    });
    

    JavaScript(旧版)

    googletag.cmd.push(function () {
      googletag.display("div-1");
    });
    

    TypeScript

    googletag.cmd.push(() => {
      googletag.display("div-1");
    });
    
    另请参阅
  • 参数
    divOrSlot: string | Element | Slot
    包含广告位或 div 元素的 div 元素的 ID,或 slot 对象。如果提供了 div 元素,该元素必须具有与传入 defineSlot 的 ID 相匹配的“id”属性。


googletagenableServices

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


googletaggetVersion

  • getVersion(): string
  • 返回当前版本的 GPT。

  • 另请参阅
  • 返回
    string
    当前正在执行的 GPT 版本字符串。


googletagopenConsole

  • 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?: string
    广告位 div ID。此值是可选的。提供此参数后,发布商控制台将尝试打开指定广告位的详细信息,并在视图中显示。


googletagpubads


googletagsetAdIframeTitle

  • setAdIframeTitle(title: string): void
  • 从现在开始,为 PubAdsService 创建的所有广告容器 iframe 设置标题。

  • 示例

    JavaScript

    googletag.setAdIframeTitle("title");
    

    JavaScript(旧版)

    googletag.setAdIframeTitle("title");
    

    TypeScript

    googletag.setAdIframeTitle("title");
    
  • 参数
    title: string
    所有广告容器 iframe 的新标题。


googletagsetConfig


googletagsizeMapping


googletagCommandArray

命令数组接受一系列函数,并按顺序调用它们。它旨在取代一个标准数组,该数组用于将要在 GPT 加载后调用的函数加入队列。

方法摘要
push
按顺序执行参数中指定的函数序列。


push

  • push(...f: Array<(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());
    });
    
  • 参数
    ...f: Array<(this: typeof globalThis) => void>
    要执行的 JavaScript 函数。运行时绑定将始终为 globalThis。考虑传递一个箭头函数来保留外围词法上下文的 this 值。
  • 返回
    number
    到目前为止已处理的命令数量。这与 Array.push 的返回值(数组的当前长度)兼容。


googletagCompanionAdsService

扩展 Service

随播广告服务。视频广告会使用此服务来展示随播广告。

方法摘要
addEventListener
通过注册监听器,您可以设置 JavaScript 函数,并在网页上发生特定 GPT 事件时调用该函数。
getSlots
获取与此服务关联的槽列表。
removeEventListener
移除以前注册的监听器。
setRefreshUnfilledSlots
设置是否让系统自动补余尚未填充的随播广告位。
另请参阅


setRefreshUnfilledSlots

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

    此方法可在网页的生命周期内多次调用以开启和关闭补余广告。只有同时在 PubAdsService 中注册的广告位才会被补余。由于政策限制,此方法无法在投放 Ad Exchange 视频时填充空白的随播广告位。

  • 示例

    JavaScript

    googletag.companionAds().setRefreshUnfilledSlots(true);
    

    JavaScript(旧版)

    googletag.companionAds().setRefreshUnfilledSlots(true);
    

    TypeScript

    googletag.companionAds().setRefreshUnfilledSlots(true);
    
  • 参数
    value: boolean
    true 用于自动回填未填充的槽,false 使它们保持不变。


googletagPrivacySettingsConfig

隐私设置的配置对象。

属性摘要
childDirectedTreatment
指明网页是否应被视为面向儿童
limitedAds
允许在受限广告模式下投放,以帮助满足发布商法规遵从方面的需求。
nonPersonalizedAds
允许投放在非个性化广告模式下投放,以满足发布商法规遵从方面的需求。
restrictDataProcessing
允许投放在受限处理模式下运行,以满足发布商法规遵从方面的需要。
trafficSource
指明请求代表的是所购流量还是自然流量。
underAgeOfConsent
指明是否将广告请求标记为来自未达到同意年龄的用户。
另请参阅


childDirectedTreatment

  • childDirectedTreatment: null | boolean
  • 指明网页是否应被视为面向儿童。设置为 null 可清除配置。


limitedAds


nonPersonalizedAds

  • nonPersonalizedAds: boolean
  • 允许投放在非个性化广告模式下投放,以满足发布商法规遵从方面的需要。


restrictDataProcessing

  • restrictDataProcessing: boolean
  • 允许投放在受限处理模式下运行,以满足发布商法规遵从的需求。


trafficSource

  • trafficSource: TrafficSource
  • 指明请求代表的是已购流量还是自然流量。此值会填充 Ad Manager 报表中的流量来源维度。如果未设置此政策,流量来源在报告中默认设为“undefined”。

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

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


underAgeOfConsent

  • underAgeOfConsent: null | boolean
  • 指明是否将广告请求标记为来自未达到同意年龄的用户。设置为 null 可清除配置。


googletagPubAdsService

扩展 Service

发布商广告服务。此服务用于提取和展示您的 Google Ad Manager 账号中的广告。

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


clear

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

    具体而言,清除广告位会将相应广告从 GPT 的长期网页浏览中移除,这样日后的请求将不会受到涉及此广告的包版或竞争性排除规则的影响。

  • 示例

    JavaScript

    const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
    googletag.display("div-1");
    const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2");
    googletag.display("div-2");
    
    // This call to clear only slot1.
    googletag.pubads().clear([slot1]);
    
    // This call to clear both slot1 and slot2.
    googletag.pubads().clear([slot1, slot2]);
    
    // This call to clear all slots.
    googletag.pubads().clear();
    

    JavaScript(旧版)

    var slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
    googletag.display("div-1");
    var slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2");
    googletag.display("div-2");
    
    // This call to clear only slot1.
    googletag.pubads().clear([slot1]);
    
    // This call to clear both slot1 and slot2.
    googletag.pubads().clear([slot1, slot2]);
    
    // This call to clear all slots.
    googletag.pubads().clear();
    

    TypeScript

    const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!;
    googletag.display("div-1");
    const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!;
    googletag.display("div-2");
    
    // This call to clear only slot1.
    googletag.pubads().clear([slot1]);
    
    // This call to clear both slot1 and slot2.
    googletag.pubads().clear([slot1, slot2]);
    
    // This call to clear all slots.
    googletag.pubads().clear();
    
  • 参数
    slots?: Slot[]
    要清除的槽数组。数组是可选的;如果未指定,系统将清除所有槽位。
  • 返回
    boolean
    如果槽已清除,则返回 true,否则返回 false


clearCategoryExclusions

  • clearCategoryExclusions(): PubAdsService
  • 清除所有网页级广告类别排除标签。如果您想刷新广告位,这会非常有用。

  • 示例

    JavaScript

    // Set category exclusion to exclude ads with 'AirlineAd' labels.
    googletag.pubads().setCategoryExclusion("AirlineAd");
    
    // Make ad requests. No ad with 'AirlineAd' label will be returned.
    
    // Clear category exclusions so all ads can be returned.
    googletag.pubads().clearCategoryExclusions();
    
    // Make ad requests. Any ad can be returned.
    

    JavaScript(旧版)

    // Set category exclusion to exclude ads with 'AirlineAd' labels.
    googletag.pubads().setCategoryExclusion("AirlineAd");
    
    // Make ad requests. No ad with 'AirlineAd' label will be returned.
    
    // Clear category exclusions so all ads can be returned.
    googletag.pubads().clearCategoryExclusions();
    
    // Make ad requests. Any ad can be returned.
    

    TypeScript

    // Set category exclusion to exclude ads with 'AirlineAd' labels.
    googletag.pubads().setCategoryExclusion("AirlineAd");
    
    // Make ad requests. No ad with 'AirlineAd' label will be returned.
    
    // Clear category exclusions so all ads can be returned.
    googletag.pubads().clearCategoryExclusions();
    
    // Make ad requests. Any ad can be returned.
    
    另请参阅
  • 返回
    PubAdsService
    调用此方法的服务对象。


clearTargeting

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

  • 示例

    JavaScript

    googletag.pubads().setTargeting("interests", "sports");
    googletag.pubads().setTargeting("colors", "blue");
    googletag.pubads().setTargeting("fruits", "apple");
    
    googletag.pubads().clearTargeting("interests");
    // Targeting 'colors' and 'fruits' are still present, while 'interests'
    // was cleared.
    
    googletag.pubads().clearTargeting();
    // All targeting has been cleared.
    

    JavaScript(旧版)

    googletag.pubads().setTargeting("interests", "sports");
    googletag.pubads().setTargeting("colors", "blue");
    googletag.pubads().setTargeting("fruits", "apple");
    
    googletag.pubads().clearTargeting("interests");
    // Targeting 'colors' and 'fruits' are still present, while 'interests'
    // was cleared.
    
    googletag.pubads().clearTargeting();
    // All targeting has been cleared.
    

    TypeScript

    googletag.pubads().setTargeting("interests", "sports");
    googletag.pubads().setTargeting("colors", "blue");
    googletag.pubads().setTargeting("fruits", "apple");
    
    googletag.pubads().clearTargeting("interests");
    // Targeting 'colors' and 'fruits' are still present, while 'interests'
    // was cleared.
    
    googletag.pubads().clearTargeting();
    // All targeting has been cleared.
    
    另请参阅
  • 参数
    key?: string
    定位参数键。键是可选的;如果未指定,系统将清除所有定位参数。
  • 返回
    PubAdsService
    调用此方法的服务对象。


collapseEmptyDivs

  • collapseEmptyDivs(collapseBeforeAdFetch?: boolean): boolean
  • 启用广告位 div,以免在没有广告内容要显示时占用网页上的任何空间。必须在启用服务之前设置此模式。

  • 另请参阅
  • 参数
    collapseBeforeAdFetch?: boolean
    是否在提取广告之前就收起广告位。此参数是可选的;如果未提供此参数,则系统将使用 false 作为默认值。
  • 返回
    boolean
    如果 div 收起模式已启用,则返回 true;如果因在服务启用后调用该方法而无法启用收起模式,则返回 false


disableInitialLoad


display

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

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

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

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


enableLazyLoad

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

    注意:SRA 中的延迟提取功能仅在所有槽都位于提取外边距时才有效。

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

    googletag.pubads().enableLazyLoad({
      // Fetch slots within 5 viewports.
      fetchMarginPercent: 500,
      // Render slots within 2 viewports.
      renderMarginPercent: 200,
      // Double the above values on mobile.
      mobileScaling: 2.0,
    });
    
    另请参阅
  • 参数
    config?: { fetchMarginPercent: number, mobileScaling: number, renderMarginPercent: number }
    Configuration 对象允许自定义延迟行为。任何省略的配置都将使用 Google 设置的默认配置,并会随着时间的推移进行调整。如需停用特定设置(例如提取外边距),请将值设置为 -1
    • fetchMarginPercent

      广告位与当前视口的最小距离在获取广告之前必须达到此视口尺寸,该距离以占视口大小的百分比表示。值为 0 表示“当广告位进入视口时”,100 表示“当广告距离 1 个视口时”,以此类推。
    • renderMarginPercent

      广告位与当前视口之间的最小距离必须在我们呈现广告之前。这样便可预提取广告,但会等待呈现和下载其他子资源。该值的工作方式类似于 fetchMarginPercent,以占视口的百分比表示。
    • mobileScaling

      移动设备上外边距的调节系数。这样,移动设备和桌面设备上就可以有不同的利润率。例如,值为 2.0 表示在移动设备上,所有外边距都会乘以 2,从而增加槽在提取和呈现之前可以达到的最小距离。


enableSingleRequest

  • enableSingleRequest(): boolean
  • 启用单一请求模式,以便同时提取多个广告。这要求在启用发布商广告位之前定义所有发布商广告位并将其添加到 PubAdsService。必须先设置单一请求模式,然后才能启用该服务。

  • 另请参阅
  • 返回
    boolean
    如果启用了单一请求模式,则返回 true;如果由于在启用服务之后调用该方法而无法启用单一请求模式,则返回 false


enableVideoAds

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


get

  • get(key: string): null | string
  • 返回与指定键相关联的 AdSense 属性的值。

  • 示例

    JavaScript

    googletag.pubads().set("adsense_background_color", "#FFFFFF");
    googletag.pubads().get("adsense_background_color");
    // Returns '#FFFFFF'.
    

    JavaScript(旧版)

    googletag.pubads().set("adsense_background_color", "#FFFFFF");
    googletag.pubads().get("adsense_background_color");
    // Returns '#FFFFFF'.
    

    TypeScript

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


getAttributeKeys

  • getAttributeKeys(): string[]
  • 返回为此服务设置的属性键。

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

    googletag.pubads().set("adsense_background_color", "#FFFFFF");
    googletag.pubads().set("adsense_border_color", "#AABBCC");
    googletag.pubads().getAttributeKeys();
    // Returns ['adsense_background_color', 'adsense_border_color'].
    
  • 返回
    string[]
    为此服务设置的属性键数组。排序未定义。


getTargeting

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

  • 示例

    JavaScript

    googletag.pubads().setTargeting("interests", "sports");
    
    googletag.pubads().getTargeting("interests");
    // Returns ['sports'].
    
    googletag.pubads().getTargeting("age");
    // Returns [] (empty array).
    

    JavaScript(旧版)

    googletag.pubads().setTargeting("interests", "sports");
    
    googletag.pubads().getTargeting("interests");
    // Returns ['sports'].
    
    googletag.pubads().getTargeting("age");
    // Returns [] (empty array).
    

    TypeScript

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


getTargetingKeys

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

  • 示例

    JavaScript

    googletag.pubads().setTargeting("interests", "sports");
    googletag.pubads().setTargeting("colors", "blue");
    
    googletag.pubads().getTargetingKeys();
    // Returns ['interests', 'colors'].
    

    JavaScript(旧版)

    googletag.pubads().setTargeting("interests", "sports");
    googletag.pubads().setTargeting("colors", "blue");
    
    googletag.pubads().getTargetingKeys();
    // Returns ['interests', 'colors'].
    

    TypeScript

    googletag.pubads().setTargeting("interests", "sports");
    googletag.pubads().setTargeting("colors", "blue");
    
    googletag.pubads().getTargetingKeys();
    // Returns ['interests', 'colors'].
    
  • 返回
    string[]
    定位键的数组。排序未定义。


isInitialLoadDisabled


refresh

  • refresh(slots?: null | Slot[], options?: { changeCorrelator: boolean }): void
  • 针对网页上的特定或所有广告位提取并展示新广告。只能在异步呈现模式下运行。

    为了确保所有浏览器都能正常运行,在调用 refresh 之前必须先调用 display 广告位。如果省略了对 display 的调用,刷新可能会出现意外行为。如果需要,可以使用 PubAdsService.disableInitialLoad 方法阻止 display 提取广告。

    刷新广告位会从 GPT 的长效网页浏览中移除旧广告,这样日后的请求便不会再受到涉及该广告的包版或竞争性排除规则的影响。

  • 示例

    JavaScript

    const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
    googletag.display("div-1");
    const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2");
    googletag.display("div-2");
    
    // This call to refresh fetches a new ad for slot1 only.
    googletag.pubads().refresh([slot1]);
    
    // This call to refresh fetches a new ad for both slot1 and slot2.
    googletag.pubads().refresh([slot1, slot2]);
    
    // This call to refresh fetches a new ad for each slot.
    googletag.pubads().refresh();
    
    // This call to refresh fetches a new ad for slot1, without changing
    // the correlator.
    googletag.pubads().refresh([slot1], { changeCorrelator: false });
    
    // This call to refresh fetches a new ad for each slot, without
    // changing the correlator.
    googletag.pubads().refresh(null, { changeCorrelator: false });
    

    JavaScript(旧版)

    var slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
    googletag.display("div-1");
    var slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2");
    googletag.display("div-2");
    
    // This call to refresh fetches a new ad for slot1 only.
    googletag.pubads().refresh([slot1]);
    
    // This call to refresh fetches a new ad for both slot1 and slot2.
    googletag.pubads().refresh([slot1, slot2]);
    
    // This call to refresh fetches a new ad for each slot.
    googletag.pubads().refresh();
    
    // This call to refresh fetches a new ad for slot1, without changing
    // the correlator.
    googletag.pubads().refresh([slot1], { changeCorrelator: false });
    
    // This call to refresh fetches a new ad for each slot, without
    // changing the correlator.
    googletag.pubads().refresh(null, { changeCorrelator: false });
    

    TypeScript

    const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!;
    googletag.display("div-1");
    const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!;
    googletag.display("div-2");
    
    // This call to refresh fetches a new ad for slot1 only.
    googletag.pubads().refresh([slot1]);
    
    // This call to refresh fetches a new ad for both slot1 and slot2.
    googletag.pubads().refresh([slot1, slot2]);
    
    // This call to refresh fetches a new ad for each slot.
    googletag.pubads().refresh();
    
    // This call to refresh fetches a new ad for slot1, without changing
    // the correlator.
    googletag.pubads().refresh([slot1], { changeCorrelator: false });
    
    // This call to refresh fetches a new ad for each slot, without
    // changing the correlator.
    googletag.pubads().refresh(null, { changeCorrelator: false });
    
    另请参阅
  • 参数
    slots?: null | Slot[]
    要刷新的槽。数组是可选的;如果未指定,系统将刷新所有槽。
    options?: { changeCorrelator: boolean }
    与此刷新调用相关的配置选项。
    • changeCorrelator

      指定是否生成新的 Correlator 用于提取广告。我们的广告服务器会短暂地维护此 Correlator 值(目前为 30 秒,但可能会发生变化),这样,在靠得很近时收到的具有相同 Correlator 的请求将被视为一次网页浏览。默认情况下,每次刷新都会生成一个新的 Correlator。

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


set

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

    针对相同键多次调用此函数会覆盖之前为该键设置的值。所有值都必须在调用 displayrefresh 之前设置。

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

    googletag.pubads().set("adsense_background_color", "#FFFFFF");
    
    另请参阅
  • 参数
    key: string
    属性的名称。
    value: string
    属性值。
  • 返回
    PubAdsService
    调用此方法的服务对象。


setCategoryExclusion

  • setCategoryExclusion(categoryExclusion: string): PubAdsService
  • 针对指定标签名称设置一个网页级广告类别排除。

  • 示例

    JavaScript

    // Label = AirlineAd.
    googletag.pubads().setCategoryExclusion("AirlineAd");
    

    JavaScript(旧版)

    // Label = AirlineAd.
    googletag.pubads().setCategoryExclusion("AirlineAd");
    

    TypeScript

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


setCentering

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

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

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

    // Make ads centered.
    googletag.pubads().setCentering(true);
    
  • 参数
    centerAds: boolean
    true:使广告居中,false 则左对齐。


setForceSafeFrame

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

    在使用此 API 时,请注意以下几点:

    • 此设置仅对相应广告位的后续广告请求生效。
    • 广告位级设置(如果指定)将始终覆盖网页级设置。
    • 如果设为 true(在广告位级或网页级),广告将始终使用 SafeFrame 容器呈现,而不会在 Google Ad Manager 界面中做出选择。
    • 不过,如果设为 false 或未指定,广告将使用 SafeFrame 容器呈现,具体取决于广告素材类型以及在 Google Ad Manager 界面中所做的选择。
    • 应谨慎使用此 API,因为它可能会影响试图突破 iframe 或依赖于直接在发布商网页中呈现的广告素材的行为。

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

    googletag.pubads().setForceSafeFrame(true);
    
    // The following slot will be opted-out of the page-level force
    // SafeFrame instruction.
    googletag
      .defineSlot("/1234567/sports", [160, 600], "div-1")!
      .setForceSafeFrame(false)
      .addService(googletag.pubads());
    
    // The following slot will have SafeFrame forced.
    googletag.defineSlot("/1234567/news", [160, 600], "div-2")!.addService(googletag.pubads());
    
    googletag.display("div-1");
    googletag.display("div-2");
    
    另请参阅
  • 参数
    forceSafeFrame: boolean
    true 可强制网页上的所有广告在 SafeFrame 中呈现,false 可将先前设置更改为 false。如果之前未指定,则设为 false 不会改变任何内容。
  • 返回
    PubAdsService
    调用函数的服务对象。


setLocation

  • setLocation(address: string): PubAdsService
  • 从网站传递位置信息,以便您可以利用地理位置定位将订单项定位到特定位置。

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

    // Postal code:
    googletag.pubads().setLocation("10001,US");
    
  • 参数
    address: string
    地址不限。
  • 返回
    PubAdsService
    调用此方法的服务对象。


setPrivacySettings

  • setPrivacySettings(privacySettings: PrivacySettingsConfig): PubAdsService
  • 允许使用配置对象通过单个 API 配置所有隐私设置。

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

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


setPublisherProvidedId

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

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

    googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
    
    另请参阅
  • 参数
    ppid: string
    发布商提供的字母数字 ID。长度必须在 32 到 150 个字符之间。
  • 返回
    PubAdsService
    调用此方法的服务对象。


setSafeFrameConfig

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

    这些网页级偏好设置将被广告位级偏好设置替换(如果指定的话)。

  • 示例

    JavaScript

    googletag.pubads().setForceSafeFrame(true);
    
    const pageConfig = {
      allowOverlayExpansion: true,
      allowPushExpansion: true,
      sandbox: true,
    };
    
    const slotConfig = { allowOverlayExpansion: false };
    
    googletag.pubads().setSafeFrameConfig(pageConfig);
    
    // The following slot will not allow for expansion by overlay.
    googletag
      .defineSlot("/1234567/sports", [160, 600], "div-1")
      .setSafeFrameConfig(slotConfig)
      .addService(googletag.pubads());
    
    // The following slot will inherit the page level settings, and hence
    // would allow for expansion by overlay.
    googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads());
    
    googletag.display("div-1");
    googletag.display("div-2");
    

    JavaScript(旧版)

    googletag.pubads().setForceSafeFrame(true);
    
    var pageConfig = {
      allowOverlayExpansion: true,
      allowPushExpansion: true,
      sandbox: true,
    };
    
    var slotConfig = { allowOverlayExpansion: false };
    
    googletag.pubads().setSafeFrameConfig(pageConfig);
    
    // The following slot will not allow for expansion by overlay.
    googletag
      .defineSlot("/1234567/sports", [160, 600], "div-1")
      .setSafeFrameConfig(slotConfig)
      .addService(googletag.pubads());
    
    // The following slot will inherit the page level settings, and hence
    // would allow for expansion by overlay.
    googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads());
    
    googletag.display("div-1");
    googletag.display("div-2");
    

    TypeScript

    googletag.pubads().setForceSafeFrame(true);
    
    const pageConfig = {
      allowOverlayExpansion: true,
      allowPushExpansion: true,
      sandbox: true,
    };
    
    const slotConfig = { allowOverlayExpansion: false };
    
    googletag.pubads().setSafeFrameConfig(pageConfig);
    
    // The following slot will not allow for expansion by overlay.
    googletag
      .defineSlot("/1234567/sports", [160, 600], "div-1")!
      .setSafeFrameConfig(slotConfig)
      .addService(googletag.pubads());
    
    // The following slot will inherit the page level settings, and hence
    // would allow for expansion by overlay.
    googletag.defineSlot("/1234567/news", [160, 600], "div-2")!.addService(googletag.pubads());
    
    googletag.display("div-1");
    googletag.display("div-2");
    
    另请参阅
  • 参数
    config: SafeFrameConfig
    配置对象。
  • 返回
    PubAdsService
    调用此方法的服务对象。


setTargeting

  • setTargeting(key: string, value: string | string[]): PubAdsService
  • 为应用于所有发布商广告服务广告位的指定键设置自定义定位参数。针对相同键多次调用此方法会覆盖旧值。这些键是在您的 Google Ad Manager 帐号中定义的。

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

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


setVideoContent

  • setVideoContent(videoContentId: string, videoCmsId: string): void
  • 设置要与广告请求一起发送的视频内容信息(用于定位和内容排除)。调用此方法时,视频广告将自动启用。对于 videoContentIdvideoCmsId,请使用向 Google Ad Manager 内容提取服务提供的值。

  • 另请参阅
  • 参数
    videoContentId: string
    视频内容 ID。
    videoCmsId: string
    视频 CMS ID。


updateCorrelator

  • updateCorrelator(): PubAdsService
  • 更改随广告请求一起发送的 Correlator,实际开始新的网页浏览。对于来自同一次网页浏览的所有广告请求,Correlator 都是相同的,但在不同的网页浏览中是唯一的。仅适用于异步模式。

    注意:这不会影响 GPT 的长期网页浏览,后者会自动反映网页上的实际广告,而且没有到期时间。

  • 示例

    JavaScript

    // Assume that the correlator is currently 12345. All ad requests made
    // by this page will currently use that value.
    
    // Replace the current correlator with a new correlator.
    googletag.pubads().updateCorrelator();
    
    // The correlator will now be a new randomly selected value, different
    // from 12345. All subsequent ad requests made by this page will use
    // the new value.
    

    JavaScript(旧版)

    // Assume that the correlator is currently 12345. All ad requests made
    // by this page will currently use that value.
    
    // Replace the current correlator with a new correlator.
    googletag.pubads().updateCorrelator();
    
    // The correlator will now be a new randomly selected value, different
    // from 12345. All subsequent ad requests made by this page will use
    // the new value.
    

    TypeScript

    // Assume that the correlator is currently 12345. All ad requests made
    // by this page will currently use that value.
    
    // Replace the current correlator with a new correlator.
    googletag.pubads().updateCorrelator();
    
    // The correlator will now be a new randomly selected value, different
    // from 12345. All subsequent ad requests made by this page will use
    // the new value.
    
  • 返回
    PubAdsService
    调用函数的服务对象。


googletagResponseInformation

表示单个广告响应的对象。

属性摘要
advertiserId
广告客户的 ID。
campaignId
广告系列的 ID。
creativeId
广告素材的 ID。
creativeTemplateId
广告的模板 ID。
lineItemId
订单项的 ID。
另请参阅


advertiserId

  • advertiserId: null | number
  • 广告客户的 ID。


campaignId

  • campaignId: null | number
  • 广告系列的 ID。


creativeId

  • creativeId: null | number
  • 广告素材的 ID。


creativeTemplateId

  • creativeTemplateId: null | number
  • 广告的模板 ID。


lineItemId

  • lineItemId: null | number
  • 订单项的 ID。


googletagRewardedPayload

一个对象,表示与激励广告相关联的奖励

属性摘要
amount
奖励中包含的商品数量。
type
奖励中包含的商品类型(例如“金币”)。
另请参阅


amount

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


type

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


googletagSafeFrameConfig

SafeFrame 容器的配置对象。

属性摘要
allowOverlayExpansion
SafeFrame 是否应允许广告内容通过叠加网页内容来展开。
allowPushExpansion
SafeFrame 是否应允许广告内容通过推送网页内容展开。
sandbox
SafeFrame 是否应使用 HTML5 沙盒属性来阻止无需用户互动的顶级导航。
useUniqueDomain
已废弃。 SafeFrame 是否应为预订型广告素材使用随机子网域。
另请参阅


allowOverlayExpansion

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


allowPushExpansion

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


sandbox

  • sandbox: boolean
  • SafeFrame 是否应使用 HTML5 沙盒属性来阻止无需用户互动的顶级导航。唯一的有效值是 true(不能强制设为 false)。请注意,沙盒属性会停用插件(如 Flash)。


useUniqueDomain

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

    注意:默认情况下,此功能处于启用状态。

  • 另请参阅


googletagService

基服务类,包含所有服务通用的方法。

方法摘要
addEventListener
通过注册监听器,您可以设置 JavaScript 函数,并在网页上发生特定 GPT 事件时调用该函数。
getSlots
获取与此服务关联的槽列表。
removeEventListener
移除以前注册的监听器。


addEventListener

  • addEventListener<K extends keyof EventTypeMap>(eventType: K, listener: (arg: EventTypeMap[K]) => void): Service
  • 通过注册监听器,您可以设置 JavaScript 函数,并在网页上发生特定 GPT 事件时调用该函数。支持以下事件:

    。在调用监听器时,系统会向监听器传递适当事件类型的对象。

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

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


getSlots

  • getSlots(): Slot[]
  • 获取与此服务关联的槽列表。

  • 返回
    Slot[]
    槽数(按槽添加到服务中的顺序)。


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
    接受单个事件对象参数的函数。


googletagSizeMappingBuilder

尺寸映射规范对象的构建器。此构建器旨在帮助轻松构建尺寸规范。

方法摘要
addSize
添加从单尺寸数组(表示视口)到表示广告位的单尺寸或多尺寸数组的映射。
build
根据添加到此构建器的映射来构建大小映射规范。
另请参阅


addSize

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

  • 示例

    JavaScript

    // Mapping 1
    googletag
      .sizeMapping()
      .addSize([1024, 768], [970, 250])
      .addSize([980, 690], [728, 90])
      .addSize([640, 480], "fluid")
      .addSize([0, 0], [88, 31]) // All viewports < 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(): null | SizeMappingArray
  • 根据添加到此构建器的映射来构建尺寸映射规范。

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

    注意:调用此方法后,构建器的行为将未定义。

  • 返回
    null | SizeMappingArray
    此构建器构建的结果。如果提供的尺寸映射无效,可为 null。


googletagSlot

广告位是表示网页上的单个广告位的对象。

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


addService

  • addService(service: Service): Slot
  • 向此槽位添加 Service

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

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


clearCategoryExclusions

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

  • 示例

    JavaScript

    // Set category exclusion to exclude ads with 'AirlineAd' labels.
    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")
      .setCategoryExclusion("AirlineAd")
      .addService(googletag.pubads());
    
    // Make an ad request. No ad with 'AirlineAd' label will be returned
    // for the slot.
    
    // Clear category exclusions so all ads can be returned.
    slot.clearCategoryExclusions();
    
    // Make an ad request. Any ad can be returned for the slot.
    

    JavaScript(旧版)

    // Set category exclusion to exclude ads with 'AirlineAd' labels.
    var slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")
      .setCategoryExclusion("AirlineAd")
      .addService(googletag.pubads());
    
    // Make an ad request. No ad with 'AirlineAd' label will be returned
    // for the slot.
    
    // Clear category exclusions so all ads can be returned.
    slot.clearCategoryExclusions();
    
    // Make an ad request. Any ad can be returned for the slot.
    

    TypeScript

    // Set category exclusion to exclude ads with 'AirlineAd' labels.
    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .setCategoryExclusion("AirlineAd")
      .addService(googletag.pubads());
    
    // Make an ad request. No ad with 'AirlineAd' label will be returned
    // for the slot.
    
    // Clear category exclusions so all ads can be returned.
    slot.clearCategoryExclusions();
    
    // Make an ad request. Any ad can be returned for the slot.
    
  • 返回
    Slot
    调用此方法的 slot 对象。


clearTargeting

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

  • 示例

    JavaScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")
      .setTargeting("allow_expandable", "true")
      .setTargeting("interests", ["sports", "music"])
      .setTargeting("color", "red")
      .addService(googletag.pubads());
    
    slot.clearTargeting("color");
    // Targeting 'allow_expandable' and 'interests' are still present,
    // while 'color' was cleared.
    
    slot.clearTargeting();
    // All targeting has been cleared.
    

    JavaScript(旧版)

    var slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")
      .setTargeting("allow_expandable", "true")
      .setTargeting("interests", ["sports", "music"])
      .setTargeting("color", "red")
      .addService(googletag.pubads());
    
    slot.clearTargeting("color");
    // Targeting 'allow_expandable' and 'interests' are still present,
    // while 'color' was cleared.
    
    slot.clearTargeting();
    // All targeting has been cleared.
    

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .setTargeting("allow_expandable", "true")
      .setTargeting("interests", ["sports", "music"])
      .setTargeting("color", "red")
      .addService(googletag.pubads());
    
    slot.clearTargeting("color");
    // Targeting 'allow_expandable' and 'interests' are still present,
    // while 'color' was cleared.
    
    slot.clearTargeting();
    // All targeting has been cleared.
    
    另请参阅
  • 参数
    key?: string
    定位参数键。键是可选的;如果未指定,系统将清除所有定位参数。
  • 返回
    Slot
    调用此方法的 slot 对象。


defineSizeMapping

  • defineSizeMapping(sizeMapping: SizeMappingArray): Slot
  • 用于设置相应广告位的尺寸(从最小视口尺寸到广告位尺寸)的映射数组。

  • 示例

    JavaScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")
      .addService(googletag.pubads());
    
    const mapping = googletag
      .sizeMapping()
      .addSize([100, 100], [88, 31])
      .addSize(
        [320, 400],
        [
          [320, 50],
          [300, 50],
        ]
      )
      .build();
    
    slot.defineSizeMapping(mapping);
    

    JavaScript(旧版)

    var slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")
      .addService(googletag.pubads());
    
    var mapping = googletag
      .sizeMapping()
      .addSize([100, 100], [88, 31])
      .addSize(
        [320, 400],
        [
          [320, 50],
          [300, 50],
        ]
      )
      .build();
    
    slot.defineSizeMapping(mapping);
    

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .addService(googletag.pubads());
    
    const mapping = googletag
      .sizeMapping()
      .addSize([100, 100], [88, 31])
      .addSize(
        [320, 400],
        [
          [320, 50],
          [300, 50],
        ]
      )
      .build();
    
    slot.defineSizeMapping(mapping!);
    
    另请参阅
  • 参数
    sizeMapping: SizeMappingArray
    尺寸映射的数组。您可以使用 SizeMappingBuilder 进行创建。每个尺寸映射都是由以下两个元素组成的数组:SingleSizeArrayGeneralSize
  • 返回
    Slot
    调用此方法的 slot 对象。


get

  • get(key: string): null | string
  • 返回与该广告位的指定键相关联的 AdSense 属性的值。如需查看此槽继承的服务级属性,请使用 PubAdsService.get

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .set("adsense_background_color", "#FFFFFF")
      .addService(googletag.pubads());
    
    slot.get("adsense_background_color");
    // Returns '#FFFFFF'.
    
    另请参阅
  • 参数
    key: string
    要查找的属性的名称。
  • 返回
    null | 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")
      .set("adsense_background_color", "#FFFFFF")
      .set("adsense_border_color", "#AABBCC")
      .addService(googletag.pubads());
    
    slot.getAttributeKeys();
    // Returns ['adsense_background_color', 'adsense_border_color'].
    

    JavaScript(旧版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .set("adsense_background_color", "#FFFFFF")
      .set("adsense_border_color", "#AABBCC")
      .addService(googletag.pubads());
    
    slot.getAttributeKeys();
    // Returns ['adsense_background_color', 'adsense_border_color'].
    
  • 返回
    string[]
    属性键数组。排序未定义。


getCategoryExclusions

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

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .setCategoryExclusion("AirlineAd")
      .setCategoryExclusion("TrainAd")
      .addService(googletag.pubads());
    
    slot.getCategoryExclusions();
    // Returns ['AirlineAd', 'TrainAd'].
    
  • 返回
    string[]
    此广告位的广告类别排除标签,如果未设置任何标签,则为空数组。


getResponseInformation

  • getResponseInformation(): null | ResponseInformation
  • 返回广告响应信息。该指标取决于相应广告位的最后一次广告响应。如果在广告位没有广告时调用此方法,将返回 null

  • 返回
    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-1'.
    

    JavaScript(旧版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .addService(googletag.pubads());
    
    slot.getSlotElementId();
    // Returns 'div-1'.
    
  • 返回
    string
    广告位 div ID。


getTargeting

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

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .setTargeting("allow_expandable", "true")
      .addService(googletag.pubads());
    
    slot.getTargeting("allow_expandable");
    // Returns ['true'].
    
    slot.getTargeting("age");
    // Returns [] (empty array).
    
  • 参数
    key: string
    要查找的定位键。
  • 返回
    string[]
    与此键关联的值,如果没有此类键,则返回空数组。


getTargetingKeys

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

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .setTargeting("allow_expandable", "true")
      .setTargeting("interests", ["sports", "music"])
      .addService(googletag.pubads());
    
    slot.getTargetingKeys();
    // Returns ['interests', 'allow_expandable'].
    
  • 返回
    string[]
    定位键的数组。排序未定义。


set

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

    针对相同键多次调用此方法会覆盖之前为该键设置的值。所有值都必须在调用 displayrefresh 之前设置。

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

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


setCategoryExclusion

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

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

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


setClickUrl

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

    即使点击跟踪网址被替换,Google Ad Manager 服务器仍会记录点击。系统会将与所投放广告素材关联的所有着陆页网址附加到提供的值。之后的调用会覆盖该值。这仅适用于非 SRA 请求。

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

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


setCollapseEmptyDiv

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

  • 示例

    JavaScript

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

    JavaScript(旧版)

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

    TypeScript

    googletag
      .defineSlot("/1234567/sports", [160, 600], "div-1")!
      .setCollapseEmptyDiv(true, true)
      .addService(googletag.pubads());
    // The above will cause the div for this slot to be collapsed
    // when the page is loaded, before ads are requested.
    
    googletag
      .defineSlot("/1234567/sports", [160, 600], "div-2")!
      .setCollapseEmptyDiv(true)
      .addService(googletag.pubads());
    // The above will cause the div for this slot to be collapsed
    // only after GPT detects that no ads are available for the slot.
    
    另请参阅
  • 参数
    collapse: boolean
    是否在未返回任何广告时合拢广告位。
    collapseBeforeAdFetch?: boolean
    是否在提取广告之前就合拢广告位。如果合拢状态不是 true,则忽略。
  • 返回
    Slot
    调用此方法的 slot 对象。


setConfig


setForceSafeFrame

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

    使用此 API 时,请注意以下几点:

    • 此设置仅对相应广告位的后续广告请求生效。
    • 广告位级设置(如果指定)将始终覆盖网页级设置。
    • 如果设为 true(在广告位级或网页级),广告将始终使用 SafeFrame 容器呈现,而不会在 Google Ad Manager 界面中做出选择。
    • 不过,如果设为 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
    调用此方法的 slot 对象。


setSafeFrameConfig

  • setSafeFrameConfig(config: null | 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: null | SafeFrameConfig
    配置对象。
  • 返回
    Slot
    调用此方法的 slot 对象。


setTargeting

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

  • 示例

    JavaScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")
      .addService(googletag.pubads());
    
    // Example with a single value for a key.
    slot.setTargeting("allow_expandable", "true");
    
    // Example with multiple values for a key inside in an array.
    slot.setTargeting("interests", ["sports", "music"]);
    

    JavaScript(旧版)

    var slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")
      .addService(googletag.pubads());
    
    // Example with a single value for a key.
    slot.setTargeting("allow_expandable", "true");
    
    // Example with multiple values for a key inside in an array.
    slot.setTargeting("interests", ["sports", "music"]);
    

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .addService(googletag.pubads());
    
    // Example with a single value for a key.
    slot.setTargeting("allow_expandable", "true");
    
    // Example with multiple values for a key inside in an array.
    slot.setTargeting("interests", ["sports", "music"]);
    
    另请参阅
  • 参数
    key: string
    定位参数键。
    value: string | string[]
    定位参数值或值数组。
  • 返回
    Slot
    调用此方法的 slot 对象。


updateTargetingFromMap

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

    注意

    • 在发生覆盖的情况下,系统将仅保留最后一个值。
    • 如果值为数组,则之前的所有值都将被覆盖,而不会合并。
    • 在此处设置的值会覆盖在服务级别设置的定位参数。

  • 示例

    JavaScript

    const slot = googletag.defineSlot("/1234567/sports", [160, 600], "div");
    
    slot.updateTargetingFromMap({
      color: "red",
      interests: ["sports", "music", "movies"],
    });
    

    JavaScript(旧版)

    var slot = googletag.defineSlot("/1234567/sports", [160, 600], "div");
    
    slot.updateTargetingFromMap({
      color: "red",
      interests: ["sports", "music", "movies"],
    });
    

    TypeScript

    const slot = googletag.defineSlot("/1234567/sports", [160, 600], "div")!;
    
    slot.updateTargetingFromMap({
      color: "red",
      interests: ["sports", "music", "movies"],
    });
    
  • 参数
    map: {  [adUnitPath: string]: string | string[] }
    定位参数的键:值映射。
  • 返回
    Slot
    调用此方法的 slot 对象。


googletagconfigAdExpansionConfig

用于控制广告展开方式的设置。

属性摘要
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 },
});


enabled


googletagconfigComponentAuctionConfig

一个对象,表示设备端广告竞价中的单个组件竞价。

属性摘要
auctionConfig
此组件竞价的竞价配置对象。
configKey
与此组件竞价相关联的配置键。
另请参阅


auctionConfig

  • auctionConfig: null | { auctionSignals: unknown, decisionLogicUrl: string, interestGroupBuyers: string[], perBuyerExperimentGroupIds: {  [buyer: string]: number }, perBuyerGroupLimits: {  [buyer: string]: number }, perBuyerSignals: {  [buyer: string]: unknown }, perBuyerTimeouts: {  [buyer: string]: number }, seller: string, sellerExperimentGroupId: number, sellerSignals: unknown, sellerTimeout: number, trustedScoringSignalsUrl: string }
  • 此组件竞价的竞价配置对象。

    如果此值设置为 null,则指定 configKey 的所有现有配置都将被删除。

  • 示例

    JavaScript

    const componentAuctionConfig = {
      // Seller URL should be https and the same as decisionLogicUrl's origin
      seller: "https://testSeller.com",
      decisionLogicUrl: "https://testSeller.com/ssp/decision-logic.js",
      interestGroupBuyers: ["https://example-buyer.com"],
      auctionSignals: { auction_signals: "auction_signals" },
      sellerSignals: { seller_signals: "seller_signals" },
      perBuyerSignals: {
        // listed on interestGroupBuyers
        "https://example-buyer.com": {
          per_buyer_signals: "per_buyer_signals",
        },
      },
    };
    
    const auctionSlot = googletag.defineSlot("/1234567/example", [160, 600]);
    
    // To add configKey to the component auction:
    auctionSlot.setConfig({
      componentAuction: [
        {
          configKey: "https://testSeller.com",
          auctionConfig: componentAuctionConfig,
        },
      ],
    });
    
    // To remove configKey from the component auction:
    auctionSlot.setConfig({
      componentAuction: [
        {
          configKey: "https://testSeller.com",
          auctionConfig: null,
        },
      ],
    });
    

    JavaScript(旧版)

    var componentAuctionConfig = {
      // Seller URL should be https and the same as decisionLogicUrl's origin
      seller: "https://testSeller.com",
      decisionLogicUrl: "https://testSeller.com/ssp/decision-logic.js",
      interestGroupBuyers: ["https://example-buyer.com"],
      auctionSignals: { auction_signals: "auction_signals" },
      sellerSignals: { seller_signals: "seller_signals" },
      perBuyerSignals: {
        // listed on interestGroupBuyers
        "https://example-buyer.com": {
          per_buyer_signals: "per_buyer_signals",
        },
      },
    };
    
    var auctionSlot = googletag.defineSlot("/1234567/example", [160, 600]);
    
    // To add configKey to the component auction:
    auctionSlot.setConfig({
      componentAuction: [
        {
          configKey: "https://testSeller.com",
          auctionConfig: componentAuctionConfig,
        },
      ],
    });
    
    // To remove configKey from the component auction:
    auctionSlot.setConfig({
      componentAuction: [
        {
          configKey: "https://testSeller.com",
          auctionConfig: null,
        },
      ],
    });
    

    TypeScript

    const componentAuctionConfig = {
      // Seller URL should be https and the same as decisionLogicUrl's origin
      seller: "https://testSeller.com",
      decisionLogicUrl: "https://testSeller.com/ssp/decision-logic.js",
      interestGroupBuyers: ["https://example-buyer.com"],
      auctionSignals: { auction_signals: "auction_signals" },
      sellerSignals: { seller_signals: "seller_signals" },
      perBuyerSignals: {
        // listed on interestGroupBuyers
        "https://example-buyer.com": {
          per_buyer_signals: "per_buyer_signals",
        },
      },
    };
    
    const auctionSlot = googletag.defineSlot("/1234567/example", [160, 600])!;
    
    // To add configKey to the component auction:
    auctionSlot.setConfig({
      componentAuction: [
        {
          configKey: "https://testSeller.com",
          auctionConfig: componentAuctionConfig,
        },
      ],
    });
    
    // To remove configKey from the component auction:
    auctionSlot.setConfig({
      componentAuction: [
        {
          configKey: "https://testSeller.com",
          auctionConfig: null,
        },
      ],
    });
    
    另请参阅


configKey

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

    此值不得为空,且应该是唯一的。如果两个 ComponentAuctionConfig 对象共用相同的 configKey 值,则最后一个要设置的配置将覆盖先前的配置。


googletagconfigInterstitialConfig

用于定义单个插页式广告位行为的对象。

属性摘要
triggers
此插页式广告的插页式广告触发器配置。


triggers

  • 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,
        },
      },
    });
    
    另请参阅


googletagconfigPageSettingsConfig

网页级设置的主配置界面。

允许通过一次 API 调用设置多项功能。

下面列出的所有属性均为示例,并不代表使用 setConfig 的实际功能。如需了解这组功能,请参阅下面的 PageSettingsConfig 类型中的字段。

示例:

  • 仅修改 setConfig 调用中指定的功能。
      // Configure feature alpha.
      googletag.setConfig({
          alpha: {...}
      });
    
      // Configure feature bravo. Feature alpha is unchanged.
      googletag.setConfig({
         bravo: {...}
      });
    
  • 每次调用 setConfig 时,指定功能的所有设置都会更新。
      // Configure feature charlie to echo = 1, foxtrot = true.
      googletag.setConfig({
          charlie: {
              echo: 1,
              foxtrot: true,
          }
      });
    
      // Update feature charlie to echo = 2. Since foxtrot was not specified,
      // the value is cleared.
      googletag.setConfig({
          charlie: {
              echo: 2
          }
      });
    
  • 传递 null 即可清除功能的所有设置。
      // Configure features delta, golf, and hotel.
      googletag.setConfig({
          delta: {...},
          golf: {...},
          hotel: {...},
      });
    
      // Feature delta and hotel are cleared, but feature golf remains set.
      googletag.setConfig({
          delta: null,
          hotel: null,
      });
    

属性摘要
adExpansion
用于控制广告展开方式的设置。
pps
用于控制发布商提供的信号 (PPS) 的设置。
privacyTreatments
用于控制发布商隐私保护处理方式的设置。


adExpansion


pps


privacyTreatments


googletagconfigPrivacyTreatmentsConfig

用于控制发布商隐私保护处理方式的设置。

属性摘要
treatments
一系列要启用的发布商隐私保护处理方式。


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


googletagconfigPublisherProvidedSignalsConfig

发布商提供的信号 (PPS) 配置对象。

属性摘要
taxonomies
包含 Taxonomy 映射的对象。
示例

JavaScript

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


taxonomies


googletagconfigSlotSettingsConfig

槽级设置的主配置接口。

通过对单个槽位的单个 API 调用设置多项功能。

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

示例:

  • 仅修改 Slot.setConfig 调用中指定的功能。
      const slot = googletag.defineSlot("/1234567/example", [160, 600]);
    
      // Configure feature alpha.
      slot.setConfig({
          alpha: {...}
      });
    
      // Configure feature bravo. Feature alpha is unchanged.
      slot.setConfig({
         bravo: {...}
      });
    
  • 每次调用 Slot.setConfig 时,指定功能的所有设置都会更新。
      // Configure feature charlie to echo = 1, foxtrot = true.
      slot.setConfig({
          charlie: {
              echo: 1,
              foxtrot: true,
          }
      });
    
      // Update feature charlie to echo = 2. Since foxtrot was not specified,
      // the value is cleared.
      slot.setConfig({
          charlie: {
              echo: 2
          }
      });
    
  • 传递 null 即可清除功能的所有设置。
      // Configure features delta, golf, and hotel.
      slot.setConfig({
          delta: {...},
          golf: {...},
          hotel: {...},
      });
    
      // Feature delta and hotel are cleared, but feature golf remains set.
      slot.setConfig({
          delta: null,
          hotel: null,
      });
    

属性摘要
adExpansion
用于控制广告展开方式的设置。
componentAuction
要纳入到设备端广告竞价中的一系列组件竞价。
interstitial
用于控制插页式广告位行为的设置。


adExpansion


componentAuction


interstitial


googletagconfigTaxonomyData

包含单个分类的值的对象。

属性摘要
values
Taxonomy 值列表。


values

  • values: string[]
  • Taxonomy 值列表。


googletageventsEvent

所有 GPT 事件的基本接口。以下所有 GPT 事件都将包含以下字段。

属性摘要
serviceName
触发事件的服务的名称。
slot
触发事件的广告位。
另请参阅


serviceName

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


slot

  • slot: Slot
  • 触发事件的广告位。


googletageventsEventTypeMap

它是一种伪类型,用于将事件名称映射到对应的 Service.addEventListenerService.removeEventListener 事件对象类型。本文档仅作参考和确保类型安全之用。

属性摘要
impressionViewable
rewardedSlotClosed
rewardedSlotGranted
rewardedSlotReady
slotOnload
events.SlotOnloadEvent 的别名。
slotRenderEnded
slotRequested
slotResponseReceived
slotVisibilityChanged


impressionViewable


rewardedSlotClosed


rewardedSlotGranted


rewardedSlotReady


slotOnload


slotRenderEnded


slotRequested


slotResponseReceived


slotVisibilityChanged


googletageventsImpressionViewableEvent

扩展 Event

当展示变为可见(根据 Active View 条件)时,会触发此事件。

属性摘要
serviceName
触发事件的服务的名称。
slot
触发事件的广告位。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

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


googletageventsRewardedSlotClosedEvent

扩展 Event

当用户关闭激励广告位时会触发此事件。它可能会在用户获得奖励之前或之后触发。如需确定是否已获得奖励,请改用 events.RewardedSlotGrantedEvent

属性摘要
serviceName
触发事件的服务的名称。
slot
触发事件的广告位。
示例

JavaScript

// This listener is called when the user closes a rewarded ad slot.
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
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(旧版)

// This listener is called when the user closes a rewarded ad slot.
var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
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

// This listener is called when the user closes a rewarded ad slot.
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
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.
  }
});
另请参阅


googletageventsRewardedSlotGrantedEvent

扩展 Event

如果因观看激励广告而获得奖励,此事件就会触发。如果在满足奖励授予标准之前关闭广告,则此事件不会触发。

属性摘要
payload
一个对象,其中包含有关已授予的奖励的信息。
serviceName
触发事件的服务的名称。
slot
触发事件的广告位。
示例

JavaScript

// This listener is called whenever a reward is granted for a
// rewarded ad.
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
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(旧版)

// This listener is called whenever a reward is granted for a
// rewarded ad.
var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
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

// This listener is called whenever a reward is granted for a
// rewarded ad.
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
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

  • payload: null | RewardedPayload
  • 一个对象,其中包含有关已授予的奖励的信息。


googletageventsRewardedSlotReadyEvent

扩展 Event

激励广告可以展示时,系统就会触发此事件。发布商负责在展示广告之前向用户显示查看广告的选项。

属性摘要
serviceName
触发事件的服务的名称。
slot
触发事件的广告位。
方法摘要
makeRewardedVisible
展示激励广告。
示例

JavaScript

// This listener is called when a rewarded ad slot becomes ready to be
// displayed.
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
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.defineSlot("/1234567/example", [160, 600]);
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.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("rewardedSlotReady", (event) => {
  const slot = event.slot;
  console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed.");

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

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


makeRewardedVisible

  • makeRewardedVisible(): void
  • 展示激励广告。在用户同意观看广告之前,请勿调用此方法。


googletageventsSlotOnloadEvent

扩展 Event

当广告素材的 iframe 触发加载事件时会触发此事件。在同步呈现模式下呈现富媒体广告时,系统不会使用 iframe,因此也不会触发 SlotOnloadEvent

属性摘要
serviceName
触发事件的服务的名称。
slot
触发事件的广告位。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

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


googletageventsSlotRenderEndedEvent

扩展 Event

将广告素材代码注入广告位时会触发此事件。此事件发生在系统抓取广告素材的资源之前,因此广告素材可能尚未显示。如果您需要了解某个广告位的所有广告素材资源何时完成加载,不妨考虑改用 events.SlotOnloadEvent

属性摘要
advertiserId
所呈现广告的广告客户 ID。
campaignId
所呈现广告的广告系列 ID。
companyIds
对呈现的补余广告出价的公司的 ID。
creativeId
已呈现的预订型广告的广告素材 ID。
creativeTemplateId
已呈现的预订型广告的广告素材模板 ID。
isBackfill
广告是否为补余广告。
isEmpty
是否针对广告位返回了广告。
labelIds
所呈现广告的标签 ID。
lineItemId
已呈现的预订型广告的订单项 ID。
serviceName
触发事件的服务的名称。
size
表示已呈现的广告素材的像素尺寸。
slot
触发事件的广告位。
slotContentChanged
广告位内容是否随所呈现的广告而发生了变化。
sourceAgnosticCreativeId
已呈现的预订型或补余广告的广告素材 ID。
sourceAgnosticLineItemId
已呈现的预订型或补余广告的订单项 ID。
yieldGroupIds
所呈现的补余广告的收益组的 ID。
示例

JavaScript

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

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

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


advertiserId

  • advertiserId: null | number
  • 所呈现广告的广告客户 ID。对于空广告位、补余广告以及由非 PubAdsService 服务呈现的广告素材,其值为 null


campaignId

  • campaignId: null | number
  • 所呈现广告的广告系列 ID。对于空广告位、补余广告以及由非 PubAdsService 服务呈现的广告素材,其值为 null


companyIds

  • companyIds: null | number[]
  • 对呈现的补余广告出价的公司的 ID。对于空广告位、预订型广告以及由非 PubAdsService 服务呈现的广告素材,该值为 null


creativeId

  • creativeId: null | number
  • 所呈现的预订型广告的广告素材 ID。对于空广告位、补余广告以及由非 PubAdsService 服务呈现的广告素材,其值为 null


creativeTemplateId

  • creativeTemplateId: null | number
  • 所呈现的预订型广告的广告素材模板 ID。对于空广告位、补余广告以及由非 PubAdsService 服务呈现的广告素材,其值为 null


isBackfill

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


isEmpty

  • isEmpty: boolean
  • 是否针对广告位返回广告。如果没有返回广告,则值为 true;否则值为 false


labelIds

  • labelIds: null | number[]
  • 所呈现广告的标签 ID。对于空广告位、补余广告以及由非 PubAdsService 服务呈现的广告素材,其值为 null


lineItemId

  • lineItemId: null | number
  • 已呈现的预订型广告的订单项 ID。对于空广告位、补余广告以及由非 PubAdsService 服务呈现的广告素材,其值为 null


size

  • size: null | string | number[]
  • 表示所呈现广告素材的像素尺寸。示例:[728, 90]。对于空广告位,值为 null


slotContentChanged

  • slotContentChanged: boolean
  • 广告位内容是否随所呈现的广告一起更改。如果内容已更改,则值为 true;否则值为 false


sourceAgnosticCreativeId

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


sourceAgnosticLineItemId

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


yieldGroupIds

  • yieldGroupIds: null | number[]
  • 所呈现的补余广告的收益组的 ID。对于空广告位、预订型广告以及由非 PubAdsService 服务呈现的广告素材,该值为 null


googletageventsSlotRequestedEvent

扩展 Event

当针对特定广告位请求广告时,会触发此事件。

属性摘要
serviceName
触发事件的服务的名称。
slot
触发事件的广告位。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

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


googletageventsSlotResponseReceived

扩展 Event

收到特定广告位的广告响应时会触发此事件。

属性摘要
serviceName
触发事件的服务的名称。
slot
触发事件的广告位。
示例

JavaScript

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

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

JavaScript(旧版)

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

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

TypeScript

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

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


googletageventsSlotVisibilityChangedEvent

扩展 Event

只要广告位的屏幕区域百分比发生变化,系统就会触发此事件。该事件会受到限制,并且触发频率不会高于每 200 毫秒一次。

属性摘要
inViewPercentage
广告可见区域所占的百分比。
serviceName
触发事件的服务的名称。
slot
触发事件的广告位。
示例

JavaScript

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

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

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

JavaScript(旧版)

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

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

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

TypeScript

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

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

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


inViewPercentage

  • inViewPercentage: number
  • 广告可见区域所占的百分比。值为 0 到 100 之间的数字。


googletagsecureSignalsBidderSignalProvider

返回特定出价方的安全信号。

出价方安全信号提供商由两部分组成:

  1. 一个收集器函数,用于返回解析为安全信号的 Promise
  2. id,用于标识与信号关联的出价方。
若要针对发布商返回安全信号,请改用 secureSignals.PublisherSignalProvider

属性摘要
collectorFunction
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>


id

  • id: string
  • 与此安全信号关联的收集器的唯一标识符,在 Google Ad Manager 中注册。


googletagsecureSignalsPublisherSignalProvider

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

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

  1. 一个收集器函数,用于返回解析为安全信号的 Promise
  2. networkCode,用于标识与信号相关联的发布商。
。若要针对出价方返回安全信号,请改用 secureSignals.BidderSignalProvider

属性摘要
collectorFunction
networkCode
与此安全信号相关联的发布商的广告联盟代码(如广告单元路径中所示)。
示例

JavaScript

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

JavaScript(旧版)

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

TypeScript

// networkCode is provided
googletag.secureSignalProviders!.push({
  networkCode: "123456",
  collectorFunction: () => {
    // ...custom signal generation logic...
    return Promise.resolve("signal");
  },
});
另请参阅


collectorFunction

  • collectorFunction: () => Promise<string>


networkCode

  • networkCode: string
  • 与此安全信号相关联的发布商的广告联盟代码(如广告单元路径中所示)。


googletagsecureSignalsSecureSignalProvidersArray

用于管理安全信号的界面。

方法摘要
clearAllCache
清除本地存储空间中的所有缓存信号。
push
向信号提供程序数组添加新的 secureSignals.SecureSignalProvider,并开始信号生成过程。


clearAllCache

  • clearAllCache(): void
  • 清除本地存储空间中的所有缓存信号。


push