GPT 參考資料

此參考資料使用 TypeScript 標記法來說明類型。下表簡要說明相關範例。

輸入運算式
string 原始字串類型。
string[] 陣列類型,其中的值只能是字串。
number | string 聯集類型,其中的值可以是數字或字串。
Array<number | string> 陣列類型,其中值為複合 (聯合) 型別。
[number, string] 元組類型,其中值是兩個元素的陣列,必須依序包含數字和字串。
Slot 物件類型,其中值為 googletag.Slot 的例項。
() => void 沒有定義引數和傳回值的函式類型。

如要進一步瞭解支援的類型和類型運算式,請參閱 TypeScript 手冊

類型註解

在變數、參數名稱、屬性名稱或函式簽名後方加上冒號,表示型別註解。類型註解會說明冒號左側元素可接受或傳回的類型。下表列出您可能會在本參考資料中看到的類型註解範例。

類型註解
param: string 表示 param 接受或傳回字串值。這個語法適用於變數、參數、屬性和傳回類型。
param?: number | string 表示 param 為選用項目,但在指定時會接受數字或字串。這個語法適用於參數和屬性。
...params: Array<() => void> 表示 params 是可接受函式的 rest 參數 。Rest 參數可接受指定類型的無限值。

googletag

Google 發布商廣告代碼用於 API 的全域命名空間。
命名空間
config
網頁層級設定的主要設定介面。
enums
這是 GPT 用於列舉類型的命名空間。
events
這是 GPT 用於事件的命名空間。
secureSignals
這是 GPT 用於管理安全信號的命名空間。
介面
CommandArray
指令陣列會接受函式序列,並依序叫用這些函式。
CompanionAdsService
隨播廣告服務。
PrivacySettingsConfig
隱私權設定的設定物件。
PubAdsService
發布商廣告服務。
ResponseInformation
代表單一廣告回應的物件。
RewardedPayload
代表與獎勵廣告相關聯的獎勵物件。
SafeFrameConfig
SafeFrame 容器的設定物件。
Service
包含所有服務通用方法的基礎服務類別。
SizeMappingBuilder
大小對應規格物件的建構工具。
Slot
版位是代表網頁上單一廣告版位的物件。
型別別名
GeneralSize
可為單一或多個尺寸的廣告版位設定有效尺寸。
MultiSize
單一有效大小的清單。
NamedSize
廣告版位可用的命名尺寸。
SingleSize
單一有效的版位大小。
SingleSizeArray
代表 [width, height] 的兩個數字陣列。
SizeMapping
可視區域大小與廣告大小的對應項目。
SizeMappingArray
大小對應項目清單。
變數
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

型別別名


GeneralSize

GeneralSize: SingleSize | MultiSize
可為單一或多個尺寸的廣告版位設定有效尺寸。

MultiSize

MultiSize: SingleSize[]
單一有效尺寸清單。

NamedSize

NamedSize: "fluid" | ["fluid"]
廣告版位可用的命名尺寸。在大多數情況下,大小是固定大小的矩形,但在某些情況下,我們需要其他類型的大小規格。只有下列命名尺寸有效:
  • fluid:廣告容器會占用父項 div 的 100% 寬度,然後調整高度,以便容納廣告素材內容。與網頁上一般區塊元素的行為類似。用於原生廣告 (請參閱相關文章)。請注意,fluid['fluid'] 都是可接受的形式,可用來宣告可變動的版位大小。

SingleSize

單一有效的版位大小。

SingleSizeArray

SingleSizeArray: [number, number]
代表 [width, height] 的兩個數字陣列。

SizeMapping

可視區域大小與廣告尺寸的對應關係。回應式廣告專用欄。

SizeMappingArray

SizeMappingArray: SizeMapping[]
大小對應項目清單。

變數


Const apiReady

apiReady: boolean | undefined
標記,指出 GPT API 已載入並可供呼叫。在 API 就緒前,這個屬性會是 undefined

請注意,建議您使用 googletag.cmd 將回呼排入佇列,以便在 GPT 就緒時執行。這些回呼不必檢查 googletag.apiReady,因為在 API 設定完成後,這些回呼一定會執行。

Const cmd

cmd: ((this: typeof globalThis) => void)[] | CommandArray
參照全域指令隊列,以便非同步執行 GPT 相關呼叫。

googletag.cmd 變數會在網頁上的 GPT 標記語法中,初始化為空的 JavaScript 陣列,而 cmd.push 是標準 Array.push 方法,可在陣列結尾新增元素。載入 GPT JavaScript 時,系統會檢查陣列,並依序執行所有函式。接著,指令碼會將 cmd 替換為 CommandArray 物件,其推送方法已定義為執行傳遞給它的函式引數。這個機制可讓 GPT 以非同步方式擷取 JavaScript,同時讓瀏覽器繼續顯示網頁,進而縮短延遲時間
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

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

Const pubadsReady

pubadsReady: boolean | undefined
此標記表示 PubAdsService 已啟用、載入且可正常運作。在呼叫 enableServices 並載入及初始化 PubAdsService 之前,這個屬性會是 undefined

secureSignalProviders

secureSignalProviders: SecureSignalProvider[] | SecureSignalProvidersArray | undefined
安全信號供應器陣列的參照。

安全信號供應器陣列會接受一連串信號產生函式,並依序叫用這些函式。這個陣列可取代標準陣列,用於將信號產生函式排入佇列,以便在 GPT 載入時呼叫
範例

JavaScript

window.googletag = window.googletag || { cmd: [] };
googletag.secureSignalProviders = googletag.secureSignalProviders || [];
googletag.secureSignalProviders.push({
  id: "collector123",
  collectorFunction: () => {
    return Promise.resolve("signal");
  },
});

JavaScript (舊版)

window.googletag = window.googletag || { cmd: [] };
googletag.secureSignalProviders = googletag.secureSignalProviders || [];
googletag.secureSignalProviders.push({
  id: "collector123",
  collectorFunction: function () {
    return Promise.resolve("signal");
  },
});

TypeScript

window.googletag = window.googletag || { cmd: [] };
googletag.secureSignalProviders = googletag.secureSignalProviders || [];
googletag.secureSignalProviders.push({
  id: "collector123",
  collectorFunction: () => {
    return Promise.resolve("signal");
  },
});
另請參閱

函式


companionAds

companionAds(): CompanionAdsService
傳回 CompanionAdsService 的參照。
傳回
CompanionAdsService隨播廣告服務。

defineOutOfPageSlot

defineOutOfPageSlot(adUnitPath: string, div?: string | OutOfPageFormat): Slot | null
使用指定廣告單元路徑建構非頁內廣告版位。

對於自訂非頁內廣告,div 是包含廣告的 div 元素 ID。詳情請參閱非頁內廣告素材相關文章。

如果是 GPT 管理的非頁內廣告,div 是支援的 OutOfPageFormat
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

// Define a GPT managed web interstitial ad slot.
googletag.defineOutOfPageSlot("/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL);
另請參閱
參數
adUnitPath: string包含聯播網代碼和廣告單元程式碼的完整廣告單元路徑
Optional div: string | OutOfPageFormat包含此廣告單元或 OutOfPageFormat 的 div ID。
傳回
Slot | null新建立的運算單元,如果無法建立運算單元,則為 null

defineSlot

defineSlot(adUnitPath: string, size: GeneralSize, div?: string): Slot | null
使用指定廣告單元路徑和大小建構廣告版位,並將其與網頁上包含廣告的 div 元素 ID 建立關聯。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
另請參閱
參數
adUnitPath: string包含聯播網代碼和單元代碼的完整廣告單元路徑
size: GeneralSize新增的版位寬度和高度。如果未提供回應式大小對應,或可視區域的大小小於對應中提供的最小大小,廣告請求就會使用這個大小。
Optional div: string包含此廣告單元的 div ID。
傳回
Slot | null新建立的運算單元,如果無法建立運算單元,則為 null

destroySlots

destroySlots(slots?: Slot[]): boolean
摧毀指定的空格,從 GPT 中移除所有相關物件和參照。此 API 不支援回傳版位和隨播版位。

在版位上呼叫此 API 會清除廣告,並從 GPT 維護的內部狀態中移除版位物件。在空白物件上呼叫任何其他函式都會導致行為不明確。請注意,如果發布商網頁保留了該版位的參照,瀏覽器可能仍不會釋放與該版位相關聯的記憶體。呼叫這個 API 後,與該版位相關聯的 div 就會可供重複使用。

特別是,移除版位會從 GPT 的長效網頁瀏覽中移除廣告,因此日後的請求不會受到涉及這則廣告的路障型廣告或競爭排除條件的影響。如果在從網頁中移除版位的 div 之前未呼叫此函式,就會導致行為不明確。
範例

JavaScript

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

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

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

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

JavaScript (舊版)

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

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

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

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

TypeScript

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

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

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

// This call to destroy all slots.
googletag.destroySlots();
參數
Optional slots: Slot[]要摧毀的格子陣列。陣列為選用項目,如未指定,則所有時段都會遭到銷毀。
傳回
boolean如果已刪除空格,則為 true,否則為 false

disablePublisherConsole

disablePublisherConsole(): void
停用 Google 發布商控制台。
另請參閱

螢幕

display(divOrSlot: string | Element | Slot): void
指示版位服務轉譯版位。每個廣告版位應只在每個網頁上顯示一次。所有空白都必須先定義,並與服務建立關聯,才能顯示。元素必須出現在 DOM 中,系統才會執行顯示呼叫。通常會將這個方法放在方法呼叫中所命名的 div 元素內的程式碼區塊中。

如果使用單一請求架構 (SRA),系統會在呼叫這個方法時,一次擷取所有未擷取的廣告版位。如要強制不顯示廣告位址,必須移除整個 div。
另請參閱
參數
divOrSlot: string | Element | Slot包含廣告位元的 div 元素 ID,或 div 元素,或廣告位元物件。如果提供 div 元素,則該元素必須具有「id」屬性,且與傳遞至 defineSlot 的 ID 相符。

enableServices

enableServices(): void
啟用網頁廣告版位已定義的所有 GPT 服務。

getVersion

getVersion(): string
傳回目前的 GPT 版本。
另請參閱
傳回
string目前執行的 GPT 版本字串。

openConsole

openConsole(div?: string): void
開啟 Google 發布商控制台。
範例

JavaScript

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

// Calling without div ID.
googletag.openConsole();

JavaScript (舊版)

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

// Calling without div ID.
googletag.openConsole();

TypeScript

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

// Calling without div ID.
googletag.openConsole();
另請參閱
參數
Optional div: string廣告版位 div ID。這個值為選用值。提供後,發布商控制台會嘗試開啟指定廣告版位中的詳細資料。

pubads

pubads(): PubAdsService
傳回 PubAdsService 的參照。
傳回
PubAdsService發布商廣告服務。

setAdIframeTitle

setAdIframeTitle(title: string): void
從此時起,為 PubAdsService 建立的所有廣告容器 iframe 設定標題。
範例

JavaScript

googletag.setAdIframeTitle("title");

JavaScript (舊版)

googletag.setAdIframeTitle("title");

TypeScript

googletag.setAdIframeTitle("title");
參數
title: string所有廣告容器 iframe 的新標題。

setConfig

setConfig(config: PageSettingsConfig): void
設定網頁的一般設定選項。
參數
config: PageSettingsConfig

sizeMapping

sizeMapping(): SizeMappingBuilder
建立新的 SizeMappingBuilder
另請參閱
傳回
SizeMappingBuilder新的建構工具。

googletag.CommandArray

指令陣列會接受函式序列,並依序叫用這些函式。這個陣列可取代標準陣列,用於在 GPT 載入後將函式加入佇列,以便在適當時間點呼叫。
方法
push
依序執行引數中指定的函式序列。

方法


push

push(...f: ((this: typeof globalThis) => void)[]): number
依序執行引數中指定的函式序列。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

googletag.cmd.push(() => {
  googletag.defineSlot("/1234567/sports", [160, 600])!.addService(googletag.pubads());
});
參數
Rest ...f: ((this: typeof globalThis) => void)[]要執行的 JavaScript 函式。執行階段繫結一律為 globalThis。建議您傳遞箭頭函式,保留包函詞彙內容的 this 值。
傳回
number目前已處理的指令數量。這與 Array.push 的傳回值 (陣列目前的長度) 相容。

googletag.CompanionAdsService

擴充 Service
隨播廣告服務。影片廣告會使用這項服務,顯示隨播廣告。
方法
addEventListener
註冊事件監聽器,讓您在網頁上發生特定 GPT 事件時,設定及呼叫 JavaScript 函式。
getSlots
取得與這項服務相關的空檔清單。
removeEventListener
移除先前註冊的事件監聽器。
setRefreshUnfilledSlots
設定是否要自動為尚未獲得廣告的隨播廣告版位補上廣告。
另請參閱

方法


setRefreshUnfilledSlots

setRefreshUnfilledSlots(value: boolean): void
設定是否要自動補上尚未填入廣告的隨播廣告版位。

這個方法可以在網頁生命週期內多次呼叫,以開啟或關閉補上廣告的功能。只有透過 PubAdsService 註冊的版位才會補上廣告。由於政策限制,這個方法無法在 Ad Exchange 影片放送時填入空白隨播廣告插播單元。
範例

JavaScript

googletag.companionAds().setRefreshUnfilledSlots(true);

JavaScript (舊版)

googletag.companionAds().setRefreshUnfilledSlots(true);

TypeScript

googletag.companionAds().setRefreshUnfilledSlots(true);
參數
value: booleantrue 可自動填補未填入的空格,false 則可保持不變。

googletag.PrivacySettingsConfig

隱私權設定的設定物件。
屬性
childDirectedTreatment?
指出是否應將該頁面視為兒童導向內容
limitedAds?
啟用「受限制的廣告」模式,協助發布商遵守法規規定。
nonPersonalizedAds?
啟用放送功能,以非個人化廣告模式運作,協助發布商遵守法規。
restrictDataProcessing?
啟用放送功能,以受限的處理模式執行,協助發布商遵守法規。
trafficSource?
指出請求是否代表購買流量或自然流量。
underAgeOfConsent?
指出是否要將廣告請求標記為來自未滿法定同意年齡的使用者。
另請參閱

屬性


Optional childDirectedTreatment

childDirectedTreatment?: null | boolean
指出是否應將該頁面視為兒童導向內容。如要清除設定,請設為 null

Optional limitedAds

limitedAds?: boolean
啟用放送模式,以便在受限制的廣告模式下放送廣告,協助發布商遵守法規。

您可以透過兩種方式指示 GPT 請求受限制的廣告:只有從受限制的廣告網址載入 GPT 時,才能手動設定受限制的廣告。如果 GPT 已從標準網址載入,嘗試修改這項設定時,系統會產生 發布商控制台警告

請注意,使用 CMP 時,您不必手動啟用受限制廣告。
範例

JavaScript

// Manually enable limited ads serving.
// GPT must be loaded from the limited ads URL to configure this setting.
googletag.pubads().setPrivacySettings({
  limitedAds: true,
});

JavaScript (舊版)

// Manually enable limited ads serving.
// GPT must be loaded from the limited ads URL to configure this setting.
googletag.pubads().setPrivacySettings({
  limitedAds: true,
});

TypeScript

// Manually enable limited ads serving.
// GPT must be loaded from the limited ads URL to configure this setting.
googletag.pubads().setPrivacySettings({
  limitedAds: true,
});
另請參閱

Optional nonPersonalizedAds

nonPersonalizedAds?: boolean
啟用放送功能,以非個人化廣告模式運作,協助發布商遵守法規。

Optional restrictDataProcessing

restrictDataProcessing?: boolean
啟用放送功能,以受限的處理模式執行,協助發布商遵守法規。

Optional trafficSource

trafficSource?: TrafficSource
指出請求是否代表購買流量或自然流量。這個值會填入 Ad Manager 報表中的「流量來源」維度。如果未設定,報表中的流量來源預設為 undefined
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

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

Optional underAgeOfConsent

underAgeOfConsent?: null | boolean
指出是否要將廣告請求標記為來自未滿法定同意年齡的使用者。如要清除設定,請設為 null

googletag.PubAdsService

擴充 Service
發布商廣告服務。這項服務可用來擷取並顯示 Google Ad Manager 帳戶中的廣告。
方法
addEventListener
註冊事件監聽器,讓您在網頁上發生特定 GPT 事件時,設定及呼叫 JavaScript 函式。
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
變更隨廣告請求傳送的關聯器,有效地開始新的網頁瀏覽。

方法


clear

clear(slots?: Slot[]): boolean
從指定的廣告位移除廣告,並用空白內容取代。系統會將這些版位標示為未擷取。

具體來說,清除版位會從 GPT 的長效網頁瀏覽中移除廣告,因此日後的請求不會受到涉及這則廣告的封鎖或競爭排除條件影響。
範例

JavaScript

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

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

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

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

JavaScript (舊版)

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

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

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

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

TypeScript

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

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

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

// This call to clear all slots.
googletag.pubads().clear();
參數
Optional slots: Slot[]要清除的空格陣列。陣列為選用項目,如果未指定,則所有時段都會清除。
傳回
boolean如果已清除插槽,就會傳回 true,否則傳回 false

clearCategoryExclusions

clearCategoryExclusions(): PubAdsService
清除所有網頁層級廣告類別排除標籤。如要重新整理時段,這個方法就很實用。
範例

JavaScript

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

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

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

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

JavaScript (舊版)

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

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

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

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

TypeScript

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

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

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

// Make ad requests. Any ad can be returned.
另請參閱
傳回
PubAdsService呼叫方法的服務物件。

clearTargeting

clearTargeting(key?: string): PubAdsService
清除特定鍵或所有鍵的自訂指定目標參數。
範例

JavaScript

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

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

googletag.pubads().clearTargeting();
// All targeting has been cleared.

JavaScript (舊版)

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

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

googletag.pubads().clearTargeting();
// All targeting has been cleared.

TypeScript

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

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

googletag.pubads().clearTargeting();
// All targeting has been cleared.
另請參閱
參數
Optional key: string指定目標參數鍵。這個鍵為選用項目,如果未指定,系統會清除所有指定目標參數。
傳回
PubAdsService呼叫方法的服務物件。

collapseEmptyDivs

collapseEmptyDivs(collapseBeforeAdFetch?: boolean): boolean
啟用廣告版位 div 收合功能,讓廣告版位在沒有廣告內容可顯示時,不會占用網頁上的任何空間。必須先設定這個模式,才能啟用服務
另請參閱
參數
Optional collapseBeforeAdFetch: boolean是否要在擷取廣告前收合廣告位。這個參數為選用,如未提供,系統會使用 false 做為預設值。
傳回
boolean如果已啟用 div 折疊模式,則會傳回 true;如果在啟用服務後呼叫方法,則無法啟用折疊模式,則會傳回 false

disableInitialLoad

disableInitialLoad(): void
在網頁載入時停用廣告請求,但允許透過 PubAdsService.refresh 呼叫要求廣告。您應在啟用服務前設定這項資訊。必須使用非同步模式,否則無法使用 refresh 要求廣告。
另請參閱

螢幕

display(adUnitPath: string, size: GeneralSize, div?: string | Element, clickUrl?: string): void
使用指定的廣告單元路徑和大小,建構並顯示廣告版位。這個方法不適用於單一請求模式。

注意:呼叫這個方法時,系統會建立廣告位址和網頁狀態的快照,以確保傳送廣告要求和算繪回應時的一致性。在這個方法呼叫後,對單元格或網頁狀態所做的任何變更 (包括指定目標、隱私權設定、強制使用 SafeFrame 等) 只會套用至後續的 display()refresh() 要求。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
另請參閱
參數
adUnitPath: string要算繪的版位廣告單元路徑
size: GeneralSize版位的寬度和高度。
Optional div: string | Element包含單元格的 div 的 ID,或 div 元素本身。
Optional clickUrl: string這個版位要使用的點擊網址。

enableLazyLoad

enableLazyLoad(config?: {
  fetchMarginPercent?: number;
  mobileScaling?: number;
  renderMarginPercent?: number;
}): void
啟用 GPT 中的延遲載入功能,如設定物件所定義。如需更詳細的範例,請參閱「延遲載入」範例。

注意:只有當所有時段都位於擷取邊界之外時,SRA 中的延遲擷取功能才會運作。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

googletag.pubads().enableLazyLoad({
  // Fetch slots within 5 viewports.
  fetchMarginPercent: 500,
  // Render slots within 2 viewports.
  renderMarginPercent: 200,
  // Double the above values on mobile.
  mobileScaling: 2.0,
});
另請參閱
參數
Optional config: {
  fetchMarginPercent?: number;
  mobileScaling?: number;
  renderMarginPercent?: number;
}
設定物件可自訂延遲行為。系統會使用 Google 的預設設定,並隨著時間調整。如要停用特定設定 (例如擷取邊界),請將值設為 -1
  • fetchMarginPercent

    廣告版位必須與目前可視區域的距離,以可視區域大小百分比表示。值為 0 表示「當版位進入可視區域時」,值為 100 表示「廣告距離可視區域 1 個單位時」,以此類推。
  • renderMarginPercent

    廣告版位必須與目前可視區域之間的最小距離,才能算出廣告顯示的時間。這可讓您預先載入廣告,但等待算繪及下載其他子資源。這個值的運作方式與 fetchMarginPercent 相同,都是以檢視區的百分比表示。
  • mobileScaling

    在行動裝置上套用邊界時使用的乘數。這樣一來,行動版和電腦版的邊框寬度就能有所不同。舉例來說,如果值為 2.0,則會在行動裝置上將所有邊距乘以 2,增加取用和算繪前可用的最小間距。

enableSingleRequest

enableSingleRequest(): boolean
啟用單一要求模式,以便同時擷取多則廣告。您必須先定義所有發布商廣告版位,並將這些版位新增至 PubAdsService,才能啟用這項服務。必須先設定單一要求模式,才能啟用服務。
另請參閱
傳回
boolean如果已啟用單一請求模式,則會傳回 true;如果方法是在服務啟用後呼叫,則無法啟用單一請求模式,則會傳回 false

enableVideoAds

enableVideoAds(): void
向 GPT 傳送信號,表示網頁上會顯示影片廣告。這樣一來,多媒體廣告和影片廣告就會啟用競爭排除限制。如果已知影片內容,請呼叫 PubAdsService.setVideoContent,以便在多媒體廣告中使用內容排除條件。

get

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

isInitialLoadDisabled(): boolean
傳回先前 PubAdsService.disableInitialLoad 呼叫是否已成功停用廣告的初始要求。
傳回
boolean如果先前對 PubAdsService.disableInitialLoad 的呼叫成功,則會傳回 true,否則傳回 false

重新整理

refresh(slots?: null | Slot[], options?: {
  changeCorrelator: boolean;
}): void
擷取並顯示網頁上特定或所有版位的全新廣告。僅適用於非同步轉譯模式。

為確保在所有瀏覽器中正常運作,請先呼叫 display 廣告位址,再呼叫 refresh。如果省略對 display 的呼叫,重新整理可能會發生非預期的行為。如有需要,您可以使用 PubAdsService.disableInitialLoad 方法,停止 display 擷取廣告。

重新整理版位會從 GPT 的長效網頁瀏覽中移除舊廣告,因此日後的請求不會受到該廣告的路障型廣告或競爭排除條件的影響。
範例

JavaScript

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

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

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

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

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

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

JavaScript (舊版)

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

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

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

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

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

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

TypeScript

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

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

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

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

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

// This call to refresh fetches a new ad for each slot, without
// changing the correlator.
googletag.pubads().refresh(null, { changeCorrelator: false });
另請參閱
參數
Optional slots: null | Slot[]要重新整理的空格。陣列為選用項目,如未指定,系統會重新整理所有時段。
Optional options: {
  changeCorrelator: boolean;
}
與此重新整理呼叫相關聯的設定選項。
  • changeCorrelator

    指定是否要為擷取廣告產生新的關聯器。我們的廣告伺服器會暫時保留這個 Correlator 值 (目前為 30 秒,但可能會變更),因此如果系統在短時間內收到具有相同 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: booleantrue 將廣告置中,false 將廣告靠左對齊。

setForceSafeFrame

setForceSafeFrame(forceSafeFrame: boolean): PubAdsService
設定是否應強制使用 SafeFrame 容器來顯示網頁上的所有廣告。

使用這個 API 時,請注意下列事項:
  • 這項設定只會影響後續針對個別廣告位元建立的廣告請求。
  • 如果指定了版位層級設定,系統一律會覆寫網頁層級設定。
  • 如果設定為 true (在版位層級或網頁層級),系統一律會使用 SafeFrame 容器顯示廣告,不受 Google Ad Manager UI 中所做的選擇影響。
  • 不過,如果設定為 false 或未指定,系統會根據廣告素材類型和 Google Ad Manager UI 中的選項,使用 SafeFrame 容器顯示廣告。
  • 請謹慎使用此 API,因為這可能會影響嘗試離開 iFrame 或需要直接在發布商網頁中顯示的廣告素材行為。
範例

JavaScript

googletag.pubads().setForceSafeFrame(true);

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

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

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

JavaScript (舊版)

googletag.pubads().setForceSafeFrame(true);

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

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

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

TypeScript

googletag.pubads().setForceSafeFrame(true);

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

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

googletag.display("div-1");
googletag.display("div-2");
另請參閱
參數
forceSafeFrame: booleantrue 可強制在 SafeFrame 中顯示網頁上的所有廣告,而 false 則可將先前的設定變更為 false。如果先前未指定,將此值設為 false 不會造成任何變化。
傳回
PubAdsService系統呼叫函式的服務物件。

setLocation

setLocation(address: string): PubAdsService
傳送網站的地理位置資訊,方便您將委刊項指定至特定地點。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

// Postal code:
googletag.pubads().setLocation("10001,US");
參數
address: string任意形式的地址。
傳回
PubAdsService呼叫方法的服務物件。

setPrivacySettings

setPrivacySettings(privacySettings: PrivacySettingsConfig): PubAdsService
允許使用設定物件,從單一 API 設定所有隱私權設定。
範例

JavaScript

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

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

// Clear the configuration for childDirectedTreatment.
googletag.pubads().setPrivacySettings({
  childDirectedTreatment: null,
});

JavaScript (舊版)

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

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

// Clear the configuration for childDirectedTreatment.
googletag.pubads().setPrivacySettings({
  childDirectedTreatment: null,
});

TypeScript

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

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

// Clear the configuration for childDirectedTreatment.
googletag.pubads().setPrivacySettings({
  childDirectedTreatment: null,
});
另請參閱
參數
privacySettings: PrivacySettingsConfig包含隱私權設定設定的物件。
傳回
PubAdsService系統呼叫函式的服務物件。

setPublisherProvidedId

setPublisherProvidedId(ppid: string): PubAdsService
設定發布商提供的 ID 值。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
另請參閱
參數
ppid: string由發布商提供的英數字元 ID。長度必須介於 32 到 150 個字元之間。
傳回
PubAdsService呼叫方法的服務物件。

setSafeFrameConfig

setSafeFrameConfig(config: SafeFrameConfig): PubAdsService
設定 SafeFrame 設定的網頁層級偏好設定。系統會忽略設定物件中無法辨識的任何鍵。如果為已辨識的鍵傳遞無效值,系統會忽略整個設定。

如果指定了版位層級偏好設定,系統會覆寫這些網頁層級偏好設定。
範例

JavaScript

googletag.pubads().setForceSafeFrame(true);

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

const slotConfig = { allowOverlayExpansion: false };

googletag.pubads().setSafeFrameConfig(pageConfig);

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

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

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

JavaScript (舊版)

googletag.pubads().setForceSafeFrame(true);

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

var slotConfig = { allowOverlayExpansion: false };

googletag.pubads().setSafeFrameConfig(pageConfig);

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

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

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

TypeScript

googletag.pubads().setForceSafeFrame(true);

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

const slotConfig = { allowOverlayExpansion: false };

googletag.pubads().setSafeFrameConfig(pageConfig);

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

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

googletag.display("div-1");
googletag.display("div-2");
另請參閱
參數
config: SafeFrameConfig設定物件。
傳回
PubAdsService呼叫方法的服務物件。

setTargeting

setTargeting(key: string, value: string | string[]): PubAdsService
為特定鍵設定自訂指定目標參數,適用於所有發布商廣告服務廣告版位。如果針對同一個鍵多次呼叫此方法,系統會覆寫舊值。這些鍵是在 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系統呼叫函式的服務物件。

googletag.ResponseInformation

代表單一廣告回應的物件。
屬性
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。

googletag.RewardedPayload

代表與獎勵廣告相關聯的獎勵物件
屬性
amount
獎勵內含的商品數量。
type
獎勵中包含的項目類型 (例如「硬幣」)。
另請參閱

屬性


金額

amount: number
獎勵內含的商品數量。

type

type: string
獎勵中包含的項目類型 (例如「硬幣」)。

googletag.SafeFrameConfig

SafeFrame 容器的設定物件。
屬性
allowOverlayExpansion?
是否允許 SafeFrame 透過疊加網頁內容,讓廣告內容擴大。
allowPushExpansion?
是否允許 SafeFrame 透過推送網頁內容,讓廣告內容展開。
sandbox?
是否要使用 HTML5 sandbox 屬性,在沒有使用者互動情況下,防止頂層導覽。
useUniqueDomain?
已淘汰。 SafeFrame 是否應為預訂廣告素材使用隨機子網域。
另請參閱

屬性


Optional allowOverlayExpansion

allowOverlayExpansion?: boolean
是否允許 SafeFrame 透過疊加網頁內容,讓廣告內容擴大。

Optional allowPushExpansion

allowPushExpansion?: boolean
是否允許 SafeFrame 透過推送網頁內容,讓廣告內容展開。

Optional sandbox

sandbox?: boolean
是否要使用 HTML5 sandbox 屬性,在沒有使用者互動情況下,防止頂層導覽。唯一有效的值是 true (無法強制設為 false)。請注意,沙箱屬性會停用外掛程式 (例如 Flash)。

Optional useUniqueDomain

useUniqueDomain?: null | boolean
是否應為預訂廣告素材使用隨機子網域。傳入 null 即可清除儲存的值。

注意:這項功能預設為啟用。
另請參閱

googletag.Service

包含所有服務通用方法的基礎服務類別。
方法
addEventListener
註冊事件監聽器,讓您在網頁上發生特定 GPT 事件時,設定及呼叫 JavaScript 函式。
getSlots
取得與這項服務相關的空檔清單。
removeEventListener
移除先前註冊的事件監聽器。

方法


addEventListener

addEventListener<K extends keyof EventTypeMap>(eventType: K, listener: ((arg: EventTypeMap[K]) => void)): Service
註冊監聽器,讓您在網頁上發生特定 GPT 事件時,設定及呼叫 JavaScript 函式。支援下列事件:在呼叫時,系統會將適當事件類型的物件傳遞至監聽器。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

// 2. Adding an event listener with slot specific logic.
// Listeners operate at service level, which means that you cannot add
// a listener for an event for a specific slot only. You can, however,
// programmatically filter a listener to respond only to a certain ad
// slot, using this pattern:
const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("slotOnload", (event) => {
  if (event.slot === targetSlot) {
    // Slot specific logic.
  }
});
另請參閱
參數
eventType: K字串,代表 GPT 產生的事件類型。事件類型會區分大小寫。
listener: ((arg: EventTypeMap[K]) => void)使用單一事件物件引數的函式。
傳回
Service呼叫方法的服務物件。

getSlots

getSlots(): Slot[]
取得與這項服務相關的空檔清單。
傳回
Slot[]按照加入服務的順序顯示空缺。

removeEventListener

removeEventListener<K extends keyof EventTypeMap>(eventType: K, listener: ((event: EventTypeMap[K]) => void)): void
移除先前註冊的事件監聽器。
範例

JavaScript

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

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

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

JavaScript (舊版)

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

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

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

TypeScript

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

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

  // Add onViewableListener as a listener for impressionViewable events.
  googletag.pubads().addEventListener("impressionViewable", onViewableListener);
  googletag.enableServices();
});
參數
eventType: K字串,代表 GPT 產生的事件類型。事件類型會區分大小寫。
listener: ((event: EventTypeMap[K]) => void)使用單一事件物件引數的函式。

googletag.SizeMappingBuilder

大小對應規格物件的建構工具。這個建構工具可協助您輕鬆建構尺寸規格。
方法
addSize
新增從單一尺寸陣列 (代表可視區域) 到單一或多種尺寸陣列 (代表版位) 的對應項目。
build
根據新增至此建構工具的對應項目,建立大小對應規格。
另請參閱

方法


addSize

addSize(viewportSize: SingleSizeArray, slotSize: GeneralSize): SizeMappingBuilder
新增從單一尺寸陣列 (代表可視區域) 到單一或多尺寸陣列 (代表版位) 的對應關係。
範例

JavaScript

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

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

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

JavaScript (舊版)

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

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

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

TypeScript

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

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

// Mapping 2 will not show any ads for the following viewport sizes:
// [1024, 768] > size >= [980, 690] and
// [640, 480] > size >= [0, 0]
參數
viewportSize: SingleSizeArray此對應項目的可視區域大小。
slotSize: GeneralSize此對應項目的資料片段大小。
傳回
SizeMappingBuilder此建構工具的參照。

build

build(): null | SizeMappingArray
根據新增至此建構工具的對應項目,建構大小對應規格。

如果提供任何無效的對應項目,這個方法會傳回 null。否則,它會以正確的格式傳回規格,以便傳遞至 Slot.defineSizeMapping

注意:呼叫此方法後,建構工具的行為未定義。
傳回
null | SizeMappingArray這個建構工具建構的結果。如果提供的大小對應無效,則可為空值。

googletag.Slot

版位是代表網頁上單一廣告版位的物件。
方法
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
服務新增至這個版位。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

googletag.defineSlot("/1234567/sports", [160, 600], "div")!.addService(googletag.pubads());
另請參閱
參數
service: Service要新增的服務。
傳回
Slot呼叫方法的空格物件。

clearCategoryExclusions

clearCategoryExclusions(): Slot
清除這個版位中的所有版位層級廣告類別排除標籤。
範例

JavaScript

// Set category exclusion to exclude ads with 'AirlineAd' labels.
const slot = googletag
  .defineSlot("/1234567/sports", [160, 600], "div")
  .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呼叫方法的空格物件。

clearTargeting

clearTargeting(key?: string): Slot
清除這個版位的特定或所有自訂版位層級指定目標參數。
範例

JavaScript

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

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

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

JavaScript (舊版)

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

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

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

TypeScript

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

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

slot.clearTargeting();
// All targeting has been cleared.
另請參閱
參數
Optional key: string指定目標參數鍵。這個鍵為選用項目,如果未指定,系統會清除所有指定目標參數。
傳回
Slot呼叫方法的空格物件。

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呼叫方法的空格物件。

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

JavaScript (舊版)

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

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

TypeScript

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

slot.getSlotElementId();
// Returns 'div'.
傳回
string時段 div ID。

getTargeting

getTargeting(key: string): string[]
傳回這個版位上特定的自訂指定參數組合。不包含服務層級指定目標參數。
範例

JavaScript

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

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

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

JavaScript (舊版)

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

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

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

TypeScript

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

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

slot.getTargeting("age");
// Returns [] (empty array).
參數
key: string要尋找的指定鍵。
傳回
string[]與此鍵相關聯的值,如果沒有此鍵,則傳回空陣列。

getTargetingKeys

getTargetingKeys(): string[]
傳回在這個版位上設定的所有自訂指定目標鍵清單。不包含服務層級指定鍵。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

slot.getTargetingKeys();
// Returns ['interests', 'allow_expandable'].
傳回
string[]指定鍵的陣列。排序未定義。

set

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呼叫方法的空格物件。

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呼叫方法的空格物件。

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呼叫方法的空格物件。

setCollapseEmptyDiv

setCollapseEmptyDiv(collapse: boolean, collapseBeforeAdFetch?: boolean): Slot
設定在廣告版位中沒有廣告時,是否應隱藏廣告版位 div。這會覆寫服務層級設定。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

googletag
  .defineSlot("/1234567/sports", [160, 600], "div-2")!
  .setCollapseEmptyDiv(true)
  .addService(googletag.pubads());
// The above will cause the div for this slot to be collapsed
// only after GPT detects that no ads are available for the slot.
另請參閱
參數
collapse: boolean是否在未傳回廣告時收合版位。
Optional collapseBeforeAdFetch: boolean即使在擷取廣告前,是否也要收合版位。如果折疊不是 true,則會遭到忽略。
傳回
Slot呼叫方法的空格物件。

setConfig

setConfig(slotConfig: SlotSettingsConfig): void
設定這個版位的一般設定選項。
參數
slotConfig: SlotSettingsConfig設定物件。

setForceSafeFrame

setForceSafeFrame(forceSafeFrame: boolean): Slot
設定是否應強制使用 SafeFrame 容器來顯示這個版位中的廣告。

使用這個 API 時,請留意下列事項:
  • 這項設定只會影響後續針對個別廣告位元建立的廣告請求。
  • 如果指定了版位層級設定,系統一律會覆寫網頁層級設定。
  • 如果設定為 true (在版位層級或網頁層級),系統一律會使用 SafeFrame 容器顯示廣告,不受 Google Ad Manager UI 中所做的選擇影響。
  • 不過,如果設定為 false 或未指定,系統會根據廣告素材類型和 Google Ad Manager UI 中的選項,使用 SafeFrame 容器顯示廣告。
  • 請謹慎使用此 API,因為這可能會影響嘗試離開 iFrame 或需要直接在發布商網頁中顯示的廣告素材行為。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

googletag
  .defineSlot("/1234567/sports", [160, 600], "div")!
  .setForceSafeFrame(true)
  .addService(googletag.pubads());
另請參閱
參數
forceSafeFrame: booleantrue 可強制在 SafeFrame 中顯示這個版位中的所有廣告,false 可選擇停用網頁層級設定 (如有)。如果未在網頁層級指定此值,將其設為 false 不會造成任何變化。
傳回
Slot呼叫方法的空格物件。

setSafeFrameConfig

setSafeFrameConfig(config: 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呼叫方法的空格物件。

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呼叫方法的空格物件。

updateTargetingFromMap

updateTargetingFromMap(map: {
  [adUnitPath: string]: string | string[];
}): Slot
根據 JSON 物件中的鍵/值對應項目,為這個版位設定自訂指定目標參數。這與為物件的所有鍵值呼叫 Slot.setTargeting 相同。這些鍵是在 Google Ad Manager 帳戶中定義。

附註:
  • 如果發生覆寫,系統只會保留最後一個值。
  • 如果值是陣列,則系統會覆寫任何先前的值,而非合併。
  • 在這裡設定的值會覆寫服務層級設定的指定目標參數。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

slot.updateTargetingFromMap({
  color: "red",
  interests: ["sports", "music", "movies"],
});
參數
map: {
  [adUnitPath: string]: string | string[];
}
指定目標參數鍵值對應。
傳回
Slot呼叫方法的空格物件。

googletag.config

網頁層級設定的主要設定介面。
介面
AdExpansionConfig
控制廣告展開功能的設定。
ComponentAuctionConfig
代表裝置端廣告競價中單一元件競價的物件。
InterstitialConfig
定義單一插播式廣告版位行為的物件。
PageSettingsConfig
網頁層級設定的主要設定介面。
PrivacyTreatmentsConfig
用於控制發布商隱私權處理方式的設定。
PublisherProvidedSignalsConfig
發布商提供的信號 (PPS) 設定物件。
SlotSettingsConfig
用於設定時段層級的設定介面。
TaxonomyData
包含單一分類方式值的物件。
型別別名
InterstitialTrigger
支援的插頁式廣告觸發條件。
PrivacyTreatment
支援的發布商隱私權處理方式。
Taxonomy

型別別名


InterstitialTrigger

InterstitialTrigger: "unhideWindow" | "navBar"
支援的插頁式廣告觸發條件。

PrivacyTreatment

PrivacyTreatment: "disablePersonalization"
支援的發布商隱私權處理方式。

分類

Taxonomy: "IAB_AUDIENCE_1_1" | "IAB_CONTENT_2_2"
發布商提供的信號 (PPS) 支援的分類。
另請參閱

googletag.config.AdExpansionConfig

控制廣告展開功能的設定。
屬性
enabled?
是否已啟用廣告展開功能。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

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

屬性


Optional 已啟用

enabled?: null | boolean
是否啟用廣告展開功能。

設定這個值會覆寫 Google Ad Manager 中預設的設定。
另請參閱

googletag.config.ComponentAuctionConfig

代表裝置端廣告競價中單一元件競價的物件。
屬性
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 值,則最後設定的值會覆寫先前的設定。

googletag.config.InterstitialConfig

定義單一插播式廣告版位行為的物件。
屬性
requireStorageAccess?
是否需要取得本機儲存空間同意聲明,才能放送這則插頁式廣告。
triggers?
插頁式廣告的插頁式觸發條件設定。

屬性


Optional requireStorageAccess

requireStorageAccess?: null | boolean
顯示此插頁式廣告是否需要取得本機儲存空間同意聲明。

GPT 會使用本機儲存空間,為插頁式廣告強制執行展示頻率上限。不過,未提供本機儲存空間同意聲明的使用者仍可看到插頁式廣告。將這項屬性設為 true 即可停用預設行為,確保插頁式廣告只會向已同意本機儲存空間的使用者顯示。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

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

Optional triggers

triggers?: null | Partial<Record<InterstitialTrigger, boolean>>
插頁式廣告的插頁式觸發事件設定。

將插頁式觸發事件的值設為 true 會啟用插頁式觸發事件,而 false 會停用插頁式觸發事件。這會覆寫在 Google Ad Manager 中設定的預設值。
範例

JavaScript

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

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

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

JavaScript (舊版)

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

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

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

TypeScript

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

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

interstitialSlot.setConfig({
  interstitial: {
    triggers: {
      navBar: enableTriggers,
      unhideWindow: enableTriggers,
    },
  },
});
另請參閱

googletag.config.PageSettingsConfig

網頁層級設定的主要設定介面。

可透過單一 API 呼叫設定多項功能。

下方列出的所有屬性均為示例,並未反映實際使用 setConfig 的功能。如需功能組合,請參閱下方 PageSettingsConfig 類型中的欄位。

範例:
  • 系統只會修改 googletag.setConfig 呼叫中指定的功能。
      // Configure feature alpha.
      googletag.setConfig({
          alpha: {...}
      });
    
      // Configure feature bravo. Feature alpha is unchanged.
      googletag.setConfig({
         bravo: {...}
      });
  • 每次呼叫 googletag.setConfig 時,系統都會更新特定功能的所有設定。
      // Configure feature charlie to echo = 1, foxtrot = true.
      googletag.setConfig({
          charlie: {
              echo: 1,
              foxtrot: true,
          }
      });
    
      // Update feature charlie to echo = 2. Since foxtrot was not specified,
      // the value is cleared.
      googletag.setConfig({
          charlie: {
              echo: 2
          }
      });
  • 您可以傳遞 null,清除功能的所有設定。
      // Configure features delta, golf, and hotel.
      googletag.setConfig({
          delta: {...},
          golf: {...},
          hotel: {...},
      });
    
      // Feature delta and hotel are cleared, but feature golf remains set.
      googletag.setConfig({
          delta: null,
          hotel: null,
      });
屬性
adExpansion?
控制廣告展開功能的設定。
adYield?
已淘汰 
pps?
用於控制發布商提供的信號 (PPS) 的設定。
privacyTreatments?
用於控制發布商隱私權處理方式的設定。
threadYield?
設定用於控管 GPT 在算繪廣告素材時是否應產生 JS 執行緒。

屬性


Optional adExpansion

adExpansion?: null | AdExpansionConfig
控制廣告展開功能的設定。

Optional adYield

adYield?: null | "DISABLED" | "ENABLED_ALL_SLOTS"

Optional pps

用於控制發布商提供的信號 (PPS) 的設定。

Optional privacyTreatments

privacyTreatments?: null | PrivacyTreatmentsConfig
用於控制發布商隱私權處理方式的設定。

Optional threadYield

threadYield?: null | "DISABLED" | "ENABLED_ALL_SLOTS"
設定可控管 GPT 在轉譯廣告素材時是否應產生 JS 執行緒。

GPT 只會產生支援 Scheduler.postTask 或 Scheduler.yield API 的瀏覽器。

支援的值:
  • null (預設):GPT 會為可視區域外部的版位產生 JS 執行緒。
  • ENABLED_ALL_SLOTS:無論單元格是否位於可視區域內,GPT 都會為所有單元格產生 JS 執行緒。
  • DISABLED:GPT 不會產生 JS 執行緒。
範例

JavaScript

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

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

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

JavaScript (舊版)

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

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

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

TypeScript

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

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

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

googletag.config.PrivacyTreatmentsConfig

用於控制發布商隱私權處理方式的設定。
屬性
treatments
要啟用的發布商隱私權處理方式陣列。

屬性


治療方式

treatments: null | "disablePersonalization"[]
要啟用的發布商隱私權處理方式陣列。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

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

googletag.config.PublisherProvidedSignalsConfig

發布商提供的信號 (PPS) 設定物件。
屬性
taxonomies
包含分類法對應項目的物件。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

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

屬性


分類法

taxonomies: Partial<Record<Taxonomy, TaxonomyData>>
包含分類法對應項目的物件。

googletag.config.SlotSettingsConfig

時段層級設定的主要設定介面。

可透過單一 API 呼叫為單一時段設定多項功能。

下方列出的所有屬性均為示例,並未反映實際使用 setConfig 的功能。如需功能組合,請參閱下方 SlotSettingsConfig 類型中的欄位。

範例:
  • 系統只會修改 Slot.setConfig 呼叫中指定的功能。
      const slot = googletag.defineSlot("/1234567/example", [160, 600]);
    
      // Configure feature alpha.
      slot.setConfig({
          alpha: {...}
      });
    
      // Configure feature bravo. Feature alpha is unchanged.
      slot.setConfig({
         bravo: {...}
      });
  • 每次呼叫 Slot.setConfig 時,系統都會更新特定功能的所有設定。
      // Configure feature charlie to echo = 1, foxtrot = true.
      slot.setConfig({
          charlie: {
              echo: 1,
              foxtrot: true,
          }
      });
    
      // Update feature charlie to echo = 2. Since foxtrot was not specified,
      // the value is cleared.
      slot.setConfig({
          charlie: {
              echo: 2
          }
      });
  • 您可以傳遞 null,清除功能的所有設定。
      // Configure features delta, golf, and hotel.
      slot.setConfig({
          delta: {...},
          golf: {...},
          hotel: {...},
      });
    
      // Feature delta and hotel are cleared, but feature golf remains set.
      slot.setConfig({
          delta: null,
          hotel: null,
      });
屬性
adExpansion?
控制廣告展開功能的設定。
componentAuction?
裝置端廣告競價中要納入的元件競價陣列。
interstitial?
控制插頁式廣告版位行為的設定。

屬性


Optional adExpansion

adExpansion?: null | AdExpansionConfig
控制廣告展開功能的設定。

Optional componentAuction

componentAuction?: null | ComponentAuctionConfig[]
裝置端廣告競價中要納入的元件競價陣列。

Optional interstitial

interstitial?: null | InterstitialConfig
用於控制插頁式廣告版位行為的設定。

googletag.config.TaxonomyData

包含單一分類方式值的物件。
屬性
values
Taxonomy 值清單。

屬性


values: string[]
Taxonomy 值清單。

googletag.enums

這是 GPT 用於列舉類型的命名空間。
列舉
OutOfPageFormat
GPT 支援的非頁內廣告格式。
TrafficSource
GPT 支援的流量來源

列舉


OutOfPageFormat

OutOfPageFormat
GPT 支援的非頁內廣告格式。
另請參閱
列舉成員
BOTTOM_ANCHOR
錨定格式,版位會固定在可視區域的底部。
GAME_MANUAL_INTERSTITIAL
手動插頁式遊戲廣告格式。

注意:手動插頁式遊戲廣告格式僅限部分對象使用
INTERSTITIAL
網頁插頁式廣告素材格式。
LEFT_SIDE_RAIL
左側邊欄格式。
REWARDED
獎勵廣告格式。
RIGHT_SIDE_RAIL
右側邊欄格式。
TOP_ANCHOR
錨點格式,版位會固定在可視區域頂端。

TrafficSource

TrafficSource
GPT 支援的流量來源
另請參閱
列舉成員
ORGANIC
直接輸入網址、網站搜尋或應用程式下載。
PURCHASED
從其他非自有資源重新導向而來的流量 (自他處取得或來自獎勵活動)。

googletag.events

這是 GPT 用於事件的命名空間。程式碼可以使用 Service.addEventListener 回應這些事件。
介面
Event
所有 GPT 事件的基本介面。
EventTypeMap
這是一個偽類型,可將事件名稱對應至 Service.addEventListenerService.removeEventListener 的對應事件物件類型。
GameManualInterstitialSlotClosedEvent
使用者關閉遊戲手動插頁式廣告時,系統會觸發這項事件。
GameManualInterstitialSlotReadyEvent
當手動插頁式遊戲廣告版位已可向使用者顯示時,系統會觸發此事件。
ImpressionViewableEvent
當曝光符合 Active View 標準時,系統就會觸發此事件。
RewardedSlotClosedEvent
使用者關閉獎勵廣告版位時,系統會觸發這個事件。
RewardedSlotGrantedEvent
使用者觀看獎勵廣告後獲得獎勵時,系統會觸發這項事件。
RewardedSlotReadyEvent
獎勵廣告準備好顯示時,系統會觸發此事件。
SlotOnloadEvent
廣告素材的 iframe 觸發載入事件時,會觸發此事件。
SlotRenderEndedEvent
廣告素材程式碼插入版位時,系統會觸發此事件。
SlotRequestedEvent
系統為特定版位要求廣告時,就會觸發這個事件。
SlotResponseReceived
系統收到特定版位的廣告回應時,就會觸發這項事件。
SlotVisibilityChangedEvent
廣告版位區域在畫面上的百分比發生變化時,系統就會觸發這個事件。

googletag.events.Event

所有 GPT 事件的基本介面。下方所有 GPT 事件都會包含下列欄位。
屬性
serviceName
觸發事件的服務名稱。
slot
觸發事件的時間間隔。
另請參閱

屬性


serviceName

serviceName: string
觸發事件的服務名稱。

slot

slot: Slot
觸發事件的時間間隔。

googletag.events.EventTypeMap

這是一個偽類型,可將事件名稱對應至 Service.addEventListenerService.removeEventListener 的對應事件物件類型。這項資訊僅供參考和型別安全性用途。
屬性
gameManualInterstitialSlotClosed
gameManualInterstitialSlotReady
impressionViewable
rewardedSlotClosed
rewardedSlotGranted
rewardedSlotReady
slotOnload
slotRenderEnded
slotRequested
slotResponseReceived
slotVisibilityChanged

屬性


gameManualInterstitialSlotClosed


gameManualInterstitialSlotReady


impressionViewable


rewardedSlotClosed


rewardedSlotGranted


rewardedSlotReady


slotOnload

slotOnload: SlotOnloadEvent
events.SlotOnloadEvent 的別名。

slotRenderEnded


slotRequested


slotResponseReceived

slotResponseReceived: SlotResponseReceived
events.SlotResponseReceived 的別名。

slotVisibilityChanged


googletag.events.GameManualInterstitialSlotClosedEvent

擴充 Event
當使用者關閉手動插頁式遊戲廣告版位時,系統會觸發這項事件。

注意:手動插頁式遊戲廣告格式僅限部分對象使用
屬性
serviceName
觸發事件的服務名稱。
slot
觸發事件的時間間隔。
範例

JavaScript

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

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

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

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

JavaScript (舊版)

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

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

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

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

TypeScript

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

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

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

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
另請參閱

googletag.events.GameManualInterstitialSlotReadyEvent

擴充 Event
當手動插頁式遊戲廣告版位已可供使用者觀看時,系統就會觸發此事件。

注意:手動插頁式遊戲廣告格式僅限部分對象使用
屬性
serviceName
觸發事件的服務名稱。
slot
觸發事件的時間間隔。
方法
makeGameManualInterstitialVisible
向使用者顯示手動插頁式遊戲廣告。
範例

JavaScript

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

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

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

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

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

JavaScript (舊版)

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

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

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

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

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

TypeScript

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

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

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

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

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
另請參閱

方法


makeGameManualInterstitialVisible

makeGameManualInterstitialVisible(): void
向使用者顯示手動插頁式遊戲廣告。

googletag.events.ImpressionViewableEvent

擴充 Event
當曝光符合 Active View 標準時,系統就會觸發此事件。
屬性
serviceName
觸發事件的服務名稱。
slot
觸發事件的時間間隔。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
另請參閱

googletag.events.RewardedSlotClosedEvent

擴充 Event
使用者關閉獎勵廣告版位時,系統會觸發這個事件。這項事件可能會在獎勵授予前或後觸發。如要判斷是否已授予獎勵,請改用 events.RewardedSlotGrantedEvent
屬性
serviceName
觸發事件的服務名稱。
slot
觸發事件的時間間隔。
範例

JavaScript

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

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

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

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

JavaScript (舊版)

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

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

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

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

TypeScript

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

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

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

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
另請參閱

googletag.events.RewardedSlotGrantedEvent

擴充 Event
使用者觀看獎勵廣告後獲得獎勵時,系統會觸發此事件。如果使用者在符合獎勵條件前關閉廣告,系統就不會觸發這項事件。
屬性
payload
包含已授予獎勵資訊的物件。
serviceName
觸發事件的服務名稱。
slot
觸發事件的時間間隔。
範例

JavaScript

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

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

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

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

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

JavaScript (舊版)

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

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

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

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

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

TypeScript

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

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

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

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

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
另請參閱

屬性


payload

payload: null | RewardedPayload
包含已授予獎勵資訊的物件。

googletag.events.RewardedSlotReadyEvent

擴充 Event
獎勵廣告準備好顯示時,系統會觸發此事件。發布商必須負責在顯示廣告前,向使用者提供觀看廣告的選項。
屬性
serviceName
觸發事件的服務名稱。
slot
觸發事件的時間間隔。
方法
makeRewardedVisible
顯示獎勵廣告。
範例

JavaScript

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

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

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

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

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

JavaScript (舊版)

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

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

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

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

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

TypeScript

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

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

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

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

    if (slot === targetSlot) {
      // Slot specific logic.
    }
  });
}
另請參閱

方法


makeRewardedVisible

makeRewardedVisible(): void
顯示獎勵廣告。使用者必須同意觀看廣告,才能呼叫這個方法。

googletag.events.SlotOnloadEvent

擴充 Event
廣告素材的 iframe 觸發載入事件時,系統會觸發此事件。在同步顯示模式中顯示多媒體廣告時,系統不會使用 iframe,因此不會觸發 SlotOnloadEvent
屬性
serviceName
觸發事件的服務名稱。
slot
觸發事件的時間間隔。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
另請參閱

googletag.events.SlotRenderEndedEvent

擴充 Event
廣告素材程式碼插入廣告位時,系統會觸發此事件。這個事件會在擷取廣告素材資源之前發生,因此廣告素材可能還未顯示。如果您需要瞭解版位所有廣告素材資源何時載入完成,請改用 events.SlotOnloadEvent
屬性
advertiserId
已算繪的廣告廣告主 ID。
campaignId
已轉譯廣告的廣告活動 ID。
companyIds
對顯示的候補廣告出價的公司 ID。
creativeId
已顯示的預留廣告廣告素材 ID。
creativeTemplateId
已算繪的預留廣告廣告素材範本 ID。
isBackfill
廣告是否為候補廣告。
isEmpty
是否已為版位傳回廣告。
labelIds
已淘汰 
lineItemId
已算繪的預訂廣告委刊項 ID。
serviceName
觸發事件的服務名稱。
size
表示算繪廣告素材的像素大小。
slot
觸發事件的時間間隔。
slotContentChanged
是否已使用算繪廣告變更版位內容。
sourceAgnosticCreativeId
已算入保留空間或候補廣告的廣告素材 ID。
sourceAgnosticLineItemId
已算入預訂或候補廣告的委刊項 ID。
yieldGroupIds
顯示的回補廣告收益群組 ID。
範例

JavaScript

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

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

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

JavaScript (舊版)

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

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

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

TypeScript

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

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

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
另請參閱

屬性


advertiserId

advertiserId: 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[]

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

googletag.events.SlotRequestedEvent

擴充 Event
系統為特定版位要求廣告時,就會觸發這項事件。
屬性
serviceName
觸發事件的服務名稱。
slot
觸發事件的時間間隔。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
另請參閱

googletag.events.SlotResponseReceived

擴充 Event
系統收到特定版位的廣告回應時,就會觸發這項事件。
屬性
serviceName
觸發事件的服務名稱。
slot
觸發事件的時間間隔。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
另請參閱

googletag.events.SlotVisibilityChangedEvent

擴充 Event
廣告版位區域在畫面上的百分比發生變化時,系統就會觸發這個事件。事件會受到節流限制,每 200 毫秒最多只會觸發一次。
屬性
inViewPercentage
可見廣告區域的百分比。
serviceName
觸發事件的服務名稱。
slot
觸發事件的時間間隔。
範例

JavaScript

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

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

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

JavaScript (舊版)

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

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

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

TypeScript

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

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

  if (slot === targetSlot) {
    // Slot specific logic.
  }
});
另請參閱

屬性


inViewPercentage

inViewPercentage: number
可見廣告區域的百分比。值為介於 0 至 100 之間的數字。

googletag.secureSignals

這是 GPT 用於管理安全信號的命名空間。
介面
BidderSignalProvider
傳回特定出價方的安全信號。
PublisherSignalProvider
傳回特定發布商的安全信號。
SecureSignalProvidersArray
用於管理安全信號的介面。
型別別名
SecureSignalProvider
針對特定出價方或供應商傳回安全信號的介面。

型別別名


SecureSignalProvider

針對特定出價方或供應商傳回安全信號的介面。必須提供 idnetworkCode 其中一個,但不能兩者都提供。

googletag.secureSignals.BidderSignalProvider

針對特定出價方傳回安全信號。

出價方安全信號供應器包含 2 個部分:

  1. 收集器函式,會傳回可解析為安全信號的 Promise
  2. id:用於識別與信號相關聯的出價方。
如要為發布商傳回安全信號,請改用 secureSignals.PublisherSignalProvider
屬性
collectorFunction
這個函式會傳回 Promise,並解析為安全信號。
id
與這個安全信號相關聯的收集器專屬 ID,已在 Google Ad Manager 中註冊。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

// id is provided
googletag.secureSignalProviders!.push({
  id: "collector123",
  collectorFunction: () => {
    // ...custom signal generation logic...
    return Promise.resolve("signal");
  },
});
另請參閱

屬性


collectorFunction

collectorFunction: (() => Promise<string>)
這個函式會傳回 Promise,並解析為安全信號。

ID

id: string
與這個安全信號相關聯的收集器專屬 ID,已在 Google Ad Manager 中註冊。

googletag.secureSignals.PublisherSignalProvider

傳回特定發布商的安全信號。

發布商信號供應者包含 2 個部分:

  1. 收集器函式,會傳回可解析為安全信號的 Promise
  2. networkCode:識別與信號相關聯的發布商。
如要為出價方傳回安全信號,請改用 secureSignals.BidderSignalProvider
屬性
collectorFunction
這個函式會傳回 Promise,並解析為安全信號。
networkCode
與這個安全信號相關聯的發布商網路代碼 (可在廣告單元路徑中看到)。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

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

屬性


collectorFunction

collectorFunction: (() => Promise<string>)
這個函式會傳回 Promise,並解析為安全信號。

networkCode

networkCode: string
與這個安全信號相關聯的發布商網路代碼 (如廣告單元路徑所示)。

googletag.secureSignals.SecureSignalProvidersArray

用於管理安全信號的介面。
方法
clearAllCache
從快取中清除所有收集器的信號。
push
將新的 secureSignals.SecureSignalProvider 新增至信號供應器陣列,並開始信號產生程序。

方法


clearAllCache

clearAllCache(): void
從快取中清除所有收集器的信號。

呼叫這個方法可能會降低信號納入目前和未來網頁瀏覽的廣告請求的可能性。因此,只有在發生有意義的狀態變更時,才應呼叫此方法,例如表示新使用者的事件 (登入、登出、註冊等)。

push

push(provider: SecureSignalProvider): void
將新的 secureSignals.SecureSignalProvider 新增至信號供應器陣列,並開始信號產生程序。
參數
provider: SecureSignalProvider要新增至陣列的 secureSignals.SecureSignalProvider 物件。