此參考資料使用 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 用於事件的命名空間。 |
secure | 這是 GPT 用於管理安全信號的命名空間。 |
介面 | |
---|---|
Command | 指令陣列會接受函式序列,並依序叫用這些函式。 |
Companion | 隨播廣告服務。 |
Privacy | 隱私權設定的設定物件。 |
Pub | 發布商廣告服務。 |
Response | 代表單一廣告回應的物件。 |
Rewarded | 代表與獎勵廣告相關聯的獎勵物件。 |
Safe | SafeFrame 容器的設定物件。 |
Service | 包含所有服務通用方法的基礎服務類別。 |
Size | 大小對應規格物件的建構工具。 |
Slot | 版位是代表網頁上單一廣告版位的物件。 |
型別別名 | |
---|---|
General | 可為單一或多個尺寸的廣告版位設定有效尺寸。 |
Multi | 單一有效大小的清單。 |
Named | 廣告版位可用的命名尺寸。 |
Single | 單一有效的版位大小。 |
Single | 代表 [width, height] 的兩個數字陣列。 |
Size | 可視區域大小與廣告大小的對應項目。 |
Size | 大小對應項目清單。 |
變數 | |
---|---|
api | 旗標,指出 GPT API 已載入並可供呼叫。 |
cmd | 參照全域指令佇列,以便非同步執行 GPT 相關呼叫。 |
pubads | 此標記表示 PubAdsService 已啟用、載入且可正常運作。 |
secure | 安全信號供應器陣列的參照。 |
函式 | |
---|---|
companion | 傳回 CompanionAdsService 的參照。 |
define | 使用指定廣告單元路徑建構非頁面內廣告版位。 |
define | 使用指定的廣告單元路徑和大小建構廣告版位,並將其與網頁上包含廣告的 div 元素 ID 建立關聯。 |
destroy | 摧毀指定的空格,從 GPT 中移除所有相關物件和參照。 |
disable | 停用 Google 發布商控制台。 |
display | 指示版位服務轉譯版位。 |
enable | 啟用網頁廣告版位已定義的所有 GPT 服務。 |
get | 傳回目前的 GPT 版本。 |
open | 開啟 Google 發布商控制台。 |
pubads | 傳回 PubAdsService 的參照。 |
set | 從此時起,為 PubAdsService 建立的所有廣告容器 iframe 設定標題。 |
set | 設定網頁的一般設定選項。 |
size | 建立新的 SizeMappingBuilder。 |
型別別名
GeneralSize
GeneralSize: SingleSize | MultiSize
MultiSize
MultiSize: SingleSize[]
NamedSize
NamedSize: "fluid" | ["fluid"]
- fluid:廣告容器會占用父項 div 的 100% 寬度,然後調整高度,以便容納廣告素材內容。與網頁上一般區塊元素的行為類似。用於原生廣告 (請參閱相關文章)。請注意,
fluid
和['fluid']
都是可接受的形式,可用來宣告可變動的版位大小。
SingleSize
SingleSize: SingleSizeArray | NamedSize
SingleSizeArray
SingleSizeArray: [number, number]
SizeMapping
SizeMapping: [SingleSizeArray, GeneralSize]
SizeMappingArray
SizeMappingArray: SizeMapping[]
變數
Const
apiReady
apiReady: boolean | undefined
undefined
。請注意,建議您使用 googletag.cmd 將回呼排入佇列,以便在 GPT 就緒時執行。這些回呼不必檢查 googletag.apiReady,因為在 API 設定完成後,這些回呼一定會執行。
Const
cmd
cmd: ((this: typeof globalThis) => void)[] | CommandArray
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
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
使用指定廣告單元路徑建構非頁內廣告版位。
對於自訂非頁內廣告,
如果是 GPT 管理的非頁內廣告,
對於自訂非頁內廣告,
div
是包含廣告的 div 元素 ID。詳情請參閱非頁內廣告素材相關文章。如果是 GPT 管理的非頁內廣告,
div
是支援的 OutOfPageFormat。- 範例
JavaScript
// Define a custom out-of-page ad slot. googletag.defineOutOfPageSlot("/1234567/sports", "div-1"); // Define a GPT managed web interstitial ad slot. googletag.defineOutOfPageSlot("/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL);
JavaScript (舊版)
// Define a custom out-of-page ad slot. googletag.defineOutOfPageSlot("/1234567/sports", "div-1"); // Define a GPT managed web interstitial ad slot. googletag.defineOutOfPageSlot("/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL);
TypeScript
// Define a custom out-of-page ad slot. googletag.defineOutOfPageSlot("/1234567/sports", "div-1"); // Define a GPT managed web interstitial ad slot. googletag.defineOutOfPageSlot("/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL);
參數 | |
---|---|
adUnitPath: string | 包含聯播網代碼和廣告單元程式碼的完整廣告單元路徑。 |
| 包含此廣告單元或 OutOfPageFormat 的 div ID。 |
傳回 | |
---|---|
Slot | null | 新建立的運算單元,如果無法建立運算單元,則為 null 。 |
defineSlot
defineSlot(adUnitPath: string, size: GeneralSize, div?: string): Slot | null
使用指定廣告單元路徑和大小建構廣告版位,並將其與網頁上包含廣告的 div 元素 ID 建立關聯。
- 範例
JavaScript
googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
JavaScript (舊版)
googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
TypeScript
googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
參數 | |
---|---|
adUnitPath: string | 包含聯播網代碼和單元代碼的完整廣告單元路徑。 |
size: GeneralSize | 新增的版位寬度和高度。如果未提供回應式大小對應,或可視區域的大小小於對應中提供的最小大小,廣告請求就會使用這個大小。 |
| 包含此廣告單元的 div ID。 |
傳回 | |
---|---|
Slot | null | 新建立的運算單元,如果無法建立運算單元,則為 null 。 |
destroySlots
destroySlots(slots?: Slot[]): boolean
摧毀指定的空格,從 GPT 中移除所有相關物件和參照。此 API 不支援回傳版位和隨播版位。
在版位上呼叫此 API 會清除廣告,並從 GPT 維護的內部狀態中移除版位物件。在空白物件上呼叫任何其他函式都會導致行為不明確。請注意,如果發布商網頁保留了該版位的參照,瀏覽器可能仍不會釋放與該版位相關聯的記憶體。呼叫這個 API 後,與該版位相關聯的 div 就會可供重複使用。
特別是,移除版位會從 GPT 的長效網頁瀏覽中移除廣告,因此日後的請求不會受到涉及這則廣告的路障型廣告或競爭排除條件的影響。如果在從網頁中移除版位的 div 之前未呼叫此函式,就會導致行為不明確。
在版位上呼叫此 API 會清除廣告,並從 GPT 維護的內部狀態中移除版位物件。在空白物件上呼叫任何其他函式都會導致行為不明確。請注意,如果發布商網頁保留了該版位的參照,瀏覽器可能仍不會釋放與該版位相關聯的記憶體。呼叫這個 API 後,與該版位相關聯的 div 就會可供重複使用。
特別是,移除版位會從 GPT 的長效網頁瀏覽中移除廣告,因此日後的請求不會受到涉及這則廣告的路障型廣告或競爭排除條件的影響。如果在從網頁中移除版位的 div 之前未呼叫此函式,就會導致行為不明確。
- 範例
JavaScript
// The calls to construct an ad and display contents. const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1"); googletag.display("div-1"); const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2"); googletag.display("div-2"); // This call to destroy only slot1. googletag.destroySlots([slot1]); // This call to destroy both slot1 and slot2. googletag.destroySlots([slot1, slot2]); // This call to destroy all slots. googletag.destroySlots();
JavaScript (舊版)
// The calls to construct an ad and display contents. var slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1"); googletag.display("div-1"); var slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2"); googletag.display("div-2"); // This call to destroy only slot1. googletag.destroySlots([slot1]); // This call to destroy both slot1 and slot2. googletag.destroySlots([slot1, slot2]); // This call to destroy all slots. googletag.destroySlots();
TypeScript
// The calls to construct an ad and display contents. const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!; googletag.display("div-1"); const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!; googletag.display("div-2"); // This call to destroy only slot1. googletag.destroySlots([slot1]); // This call to destroy both slot1 and slot2. googletag.destroySlots([slot1, slot2]); // This call to destroy all slots. googletag.destroySlots();
參數 | |
---|---|
| 要摧毀的格子陣列。陣列為選用項目,如未指定,則所有時段都會遭到銷毀。 |
傳回 | |
---|---|
boolean | 如果已刪除空格,則為 true ,否則為 false 。 |
disablePublisherConsole
disablePublisherConsole(): void
停用 Google 發布商控制台。
- 另請參閱
螢幕
display(divOrSlot: string | Element | Slot): void
指示版位服務轉譯版位。每個廣告版位應只在每個網頁上顯示一次。所有空白都必須先定義,並與服務建立關聯,才能顯示。元素必須出現在 DOM 中,系統才會執行顯示呼叫。通常會將這個方法放在方法呼叫中所命名的 div 元素內的程式碼區塊中。
如果使用單一請求架構 (SRA),系統會在呼叫這個方法時,一次擷取所有未擷取的廣告版位。如要強制不顯示廣告位址,必須移除整個 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();
- 另請參閱
參數 | |
---|---|
| 廣告版位 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
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()); });
參數 | |
---|---|
| 要執行的 JavaScript 函式。執行階段繫結一律為 globalThis 。建議您傳遞箭頭函式,保留包函詞彙內容的 this 值。 |
傳回 | |
---|---|
number | 目前已處理的指令數量。這與 Array.push 的傳回值 (陣列目前的長度) 相容。 |
googletag.CompanionAdsService
擴充隨播廣告服務。影片廣告會使用這項服務,顯示隨播廣告。
方法 | |
---|---|
add | 註冊事件監聽器,讓您在網頁上發生特定 GPT 事件時,設定及呼叫 JavaScript 函式。 沿用自 |
get | 取得與這項服務相關的空檔清單。 沿用自 |
remove | 移除先前註冊的事件監聽器。 沿用自 |
set | 設定是否要自動為尚未獲得廣告的隨播廣告版位補上廣告。 |
- 另請參閱
方法
setRefreshUnfilledSlots
setRefreshUnfilledSlots(value: boolean): void
設定是否要自動補上尚未填入廣告的隨播廣告版位。
這個方法可以在網頁生命週期內多次呼叫,以開啟或關閉補上廣告的功能。只有透過 PubAdsService 註冊的版位才會補上廣告。由於政策限制,這個方法無法在 Ad Exchange 影片放送時填入空白隨播廣告插播單元。
這個方法可以在網頁生命週期內多次呼叫,以開啟或關閉補上廣告的功能。只有透過 PubAdsService 註冊的版位才會補上廣告。由於政策限制,這個方法無法在 Ad Exchange 影片放送時填入空白隨播廣告插播單元。
- 範例
JavaScript
googletag.companionAds().setRefreshUnfilledSlots(true);
JavaScript (舊版)
googletag.companionAds().setRefreshUnfilledSlots(true);
TypeScript
googletag.companionAds().setRefreshUnfilledSlots(true);
參數 | |
---|---|
value: boolean | true 可自動填補未填入的空格,false 則可保持不變。 |
googletag.PrivacySettingsConfig
隱私權設定的設定物件。
屬性 | |
---|---|
child | 指出是否應將該頁面視為兒童導向內容。 |
limited | |
non | 啟用放送功能,以非個人化廣告模式運作,協助發布商遵守法規。 |
restrict | 啟用放送功能,以受限的處理模式執行,協助發布商遵守法規。 |
traffic | 指出請求是否代表購買流量或自然流量。 |
under | 指出是否要將廣告請求標記為來自未滿法定同意年齡的使用者。 |
- 另請參閱
屬性
Optional
childDirectedTreatment
Optional
limitedAds
limitedAds?: boolean
您可以透過兩種方式指示 GPT 請求受限制的廣告:
- 自動使用 IAB 資訊公開和同意聲明架構第 2.0 版 同意聲明管理平台的信號。
- 手動將這個欄位的值設為
true
。
請注意,使用 CMP 時,您不必手動啟用受限制廣告。
- 範例
JavaScript
// Manually enable limited ads serving. // GPT must be loaded from the limited ads URL to configure this setting. googletag.pubads().setPrivacySettings({ limitedAds: true, });
JavaScript (舊版)
// Manually enable limited ads serving. // GPT must be loaded from the limited ads URL to configure this setting. googletag.pubads().setPrivacySettings({ limitedAds: true, });
TypeScript
// Manually enable limited ads serving. // GPT must be loaded from the limited ads URL to configure this setting. googletag.pubads().setPrivacySettings({ limitedAds: true, });
- 另請參閱
Optional
nonPersonalizedAds
nonPersonalizedAds?: boolean
Optional
restrictDataProcessing
restrictDataProcessing?: boolean
Optional
trafficSource
trafficSource?: TrafficSource
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
googletag.PubAdsService
擴充發布商廣告服務。這項服務可用來擷取並顯示 Google Ad Manager 帳戶中的廣告。
方法 | |
---|---|
add | 註冊事件監聽器,讓您在網頁上發生特定 GPT 事件時,設定及呼叫 JavaScript 函式。 沿用自 |
clear | 從指定的廣告位移除廣告,並用空白內容取代。 |
clear | 清除所有網頁層級廣告類別排除標籤。 |
clear | 清除特定鍵或所有鍵的自訂指定目標參數。 |
collapse | 啟用廣告版位 div 收合功能,讓廣告版位在沒有廣告內容可顯示時,不會佔用網頁上的任何空間。 |
disable | 在網頁載入時停用廣告請求,但允許透過 PubAdsService.refresh 呼叫要求廣告。 |
display | 使用指定的廣告單元路徑和大小,建構並顯示廣告版位。 |
enable | 啟用 GPT 中的延遲載入功能,並依據設定物件定義。 |
enable | 啟用單一要求模式,以便同時擷取多則廣告。 |
enable | 向 GPT 傳達信號,表示網頁上會顯示影片廣告。 |
get | 傳回與指定鍵相關聯的 AdSense 屬性值。 |
get | 傳回已在這個服務上設定的屬性鍵。 |
get | 取得與這項服務相關的空檔清單。 沿用自 |
get | 傳回已設定的特定自訂服務層級指定參數。 |
get | 傳回已設定的所有自訂服務層級指定目標鍵清單。 |
is | 傳回先前 PubAdsService.disableInitialLoad 呼叫是否已成功停用廣告的初始要求。 |
refresh | 擷取並顯示網頁上特定或所有版位的全新廣告。 |
remove | 移除先前註冊的事件監聽器。 沿用自 |
set | 為 AdSense 屬性設定值,這些值會套用至發布商廣告服務下的所有廣告版位。 |
set | 為指定的標籤名稱設定網頁層級廣告類別排除條件。 |
set | 啟用或停用水平置中廣告。 |
set | 設定是否應強制使用 SafeFrame 容器來顯示網頁上的所有廣告。 |
set | 傳送網站的位置資訊,讓您將委刊項指定到特定地理區域。 |
set | 允許使用設定物件,從單一 API 設定所有隱私權設定。 |
set | 設定發布商提供 ID 的值。 |
set | 設定 SafeFrame 設定的網頁層級偏好設定。 |
set | 為特定鍵設定自訂指定目標參數,適用於所有發布商廣告服務廣告版位。 |
set | 設定要與廣告請求一併傳送的影片內容資訊,以便指定目標和排除內容。 |
update | 變更隨廣告請求傳送的關聯器,有效地開始新的網頁瀏覽。 |
方法
clear
clear(slots?: Slot[]): boolean
從指定的廣告位移除廣告,並用空白內容取代。系統會將這些版位標示為未擷取。
具體來說,清除版位會從 GPT 的長效網頁瀏覽中移除廣告,因此日後的請求不會受到涉及這則廣告的封鎖或競爭排除條件影響。
具體來說,清除版位會從 GPT 的長效網頁瀏覽中移除廣告,因此日後的請求不會受到涉及這則廣告的封鎖或競爭排除條件影響。
- 範例
JavaScript
const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1"); googletag.display("div-1"); const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2"); googletag.display("div-2"); // This call to clear only slot1. googletag.pubads().clear([slot1]); // This call to clear both slot1 and slot2. googletag.pubads().clear([slot1, slot2]); // This call to clear all slots. googletag.pubads().clear();
JavaScript (舊版)
var slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1"); googletag.display("div-1"); var slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2"); googletag.display("div-2"); // This call to clear only slot1. googletag.pubads().clear([slot1]); // This call to clear both slot1 and slot2. googletag.pubads().clear([slot1, slot2]); // This call to clear all slots. googletag.pubads().clear();
TypeScript
const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!; googletag.display("div-1"); const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!; googletag.display("div-2"); // This call to clear only slot1. googletag.pubads().clear([slot1]); // This call to clear both slot1 and slot2. googletag.pubads().clear([slot1, slot2]); // This call to clear all slots. googletag.pubads().clear();
參數 | |
---|---|
| 要清除的空格陣列。陣列為選用項目,如果未指定,則所有時段都會清除。 |
傳回 | |
---|---|
boolean | 如果已清除插槽,就會傳回 true ,否則傳回 false 。 |
clearCategoryExclusions
clearCategoryExclusions(): PubAdsService
清除所有網頁層級廣告類別排除標籤。如要重新整理時段,這個方法就很實用。
- 範例
JavaScript
// Set category exclusion to exclude ads with 'AirlineAd' labels. googletag.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.
- 另請參閱
參數 | |
---|---|
| 指定目標參數鍵。這個鍵為選用項目,如果未指定,系統會清除所有指定目標參數。 |
傳回 | |
---|---|
PubAdsService | 呼叫方法的服務物件。 |
collapseEmptyDivs
collapseEmptyDivs(collapseBeforeAdFetch?: boolean): boolean
啟用廣告版位 div 收合功能,讓廣告版位在沒有廣告內容可顯示時,不會占用網頁上的任何空間。必須先設定這個模式,才能啟用服務
- 。
- 另請參閱
參數 | |
---|---|
| 是否要在擷取廣告前收合廣告位。這個參數為選用,如未提供,系統會使用 false 做為預設值。 |
傳回 | |
---|---|
boolean | 如果已啟用 div 折疊模式,則會傳回 true ;如果在啟用服務後呼叫方法,則無法啟用折疊模式,則會傳回 false 。 |
disableInitialLoad
disableInitialLoad(): void
螢幕
display(adUnitPath: string, size: GeneralSize, div?: string | Element, clickUrl?: string): void
使用指定的廣告單元路徑和大小,建構並顯示廣告版位。這個方法不適用於單一請求模式。
注意:呼叫這個方法時,系統會建立廣告位址和網頁狀態的快照,以確保傳送廣告要求和算繪回應時的一致性。在這個方法呼叫後,對單元格或網頁狀態所做的任何變更 (包括指定目標、隱私權設定、強制使用 SafeFrame 等) 只會套用至後續的
注意:呼叫這個方法時,系統會建立廣告位址和網頁狀態的快照,以確保傳送廣告要求和算繪回應時的一致性。在這個方法呼叫後,對單元格或網頁狀態所做的任何變更 (包括指定目標、隱私權設定、強制使用 SafeFrame 等) 只會套用至後續的
display()
或 refresh()
要求。- 範例
JavaScript
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
JavaScript (舊版)
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
TypeScript
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
- 另請參閱
參數 | |
---|---|
adUnitPath: string | 要算繪的版位廣告單元路徑。 |
size: GeneralSize | 版位的寬度和高度。 |
| 包含單元格的 div 的 ID,或 div 元素本身。 |
| 這個版位要使用的點擊網址。 |
enableLazyLoad
enableLazyLoad(config?: {
fetchMarginPercent?: number;
mobileScaling?: number;
renderMarginPercent?: number;
}): void
啟用 GPT 中的延遲載入功能,如設定物件所定義。如需更詳細的範例,請參閱「延遲載入」範例。
注意:只有當所有時段都位於擷取邊界之外時,SRA 中的延遲擷取功能才會運作。
注意:只有當所有時段都位於擷取邊界之外時,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, });
- 另請參閱
參數 | |
---|---|
| 設定物件可自訂延遲行為。系統會使用 Google 的預設設定,並隨著時間調整。如要停用特定設定 (例如擷取邊界),請將值設為 -1 。
|
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
擷取並顯示網頁上特定或所有版位的全新廣告。僅適用於非同步轉譯模式。
為確保在所有瀏覽器中正常運作,請先呼叫
重新整理版位會從 GPT 的長效網頁瀏覽中移除舊廣告,因此日後的請求不會受到該廣告的路障型廣告或競爭排除條件的影響。
為確保在所有瀏覽器中正常運作,請先呼叫
display
廣告位址,再呼叫 refresh
。如果省略對 display
的呼叫,重新整理可能會發生非預期的行為。如有需要,您可以使用 PubAdsService.disableInitialLoad 方法,停止 display
擷取廣告。重新整理版位會從 GPT 的長效網頁瀏覽中移除舊廣告,因此日後的請求不會受到該廣告的路障型廣告或競爭排除條件的影響。
- 範例
JavaScript
const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1"); googletag.display("div-1"); const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2"); googletag.display("div-2"); // This call to refresh fetches a new ad for slot1 only. googletag.pubads().refresh([slot1]); // This call to refresh fetches a new ad for both slot1 and slot2. googletag.pubads().refresh([slot1, slot2]); // This call to refresh fetches a new ad for each slot. googletag.pubads().refresh(); // This call to refresh fetches a new ad for slot1, without changing // the correlator. googletag.pubads().refresh([slot1], { changeCorrelator: false }); // This call to refresh fetches a new ad for each slot, without // changing the correlator. googletag.pubads().refresh(null, { changeCorrelator: false });
JavaScript (舊版)
var slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1"); googletag.display("div-1"); var slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2"); googletag.display("div-2"); // This call to refresh fetches a new ad for slot1 only. googletag.pubads().refresh([slot1]); // This call to refresh fetches a new ad for both slot1 and slot2. googletag.pubads().refresh([slot1, slot2]); // This call to refresh fetches a new ad for each slot. googletag.pubads().refresh(); // This call to refresh fetches a new ad for slot1, without changing // the correlator. googletag.pubads().refresh([slot1], { changeCorrelator: false }); // This call to refresh fetches a new ad for each slot, without // changing the correlator. googletag.pubads().refresh(null, { changeCorrelator: false });
TypeScript
const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!; googletag.display("div-1"); const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!; googletag.display("div-2"); // This call to refresh fetches a new ad for slot1 only. googletag.pubads().refresh([slot1]); // This call to refresh fetches a new ad for both slot1 and slot2. googletag.pubads().refresh([slot1, slot2]); // This call to refresh fetches a new ad for each slot. googletag.pubads().refresh(); // This call to refresh fetches a new ad for slot1, without changing // the correlator. googletag.pubads().refresh([slot1], { changeCorrelator: false }); // This call to refresh fetches a new ad for each slot, without // changing the correlator. googletag.pubads().refresh(null, { changeCorrelator: false });
- 另請參閱
參數 | |
---|---|
| 要重新整理的空格。陣列為選用項目,如未指定,系統會重新整理所有時段。 |
| 與此重新整理呼叫相關聯的設定選項。
|
set
set(key: string, value: string): PubAdsService
為適用於發布商廣告服務下所有廣告版位的 AdSense 屬性設定值。
如果針對同一個鍵多次呼叫此方法,系統會覆寫先前為該鍵設定的值。必須先設定所有值,才能呼叫
如果針對同一個鍵多次呼叫此方法,系統會覆寫先前為該鍵設定的值。必須先設定所有值,才能呼叫
display
或 refresh
。- 範例
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 中,系統預設會啟用置中功能。
您應在呼叫
您應在呼叫
display
或 refresh
之前叫用此方法,因為只有在呼叫此方法後要求的廣告才會置中。- 範例
JavaScript
// Make ads centered. googletag.pubads().setCentering(true);
JavaScript (舊版)
// Make ads centered. googletag.pubads().setCentering(true);
TypeScript
// Make ads centered. googletag.pubads().setCentering(true);
參數 | |
---|---|
centerAds: boolean | true 將廣告置中,false 將廣告靠左對齊。 |
setForceSafeFrame
setForceSafeFrame(forceSafeFrame: boolean): PubAdsService
設定是否應強制使用 SafeFrame 容器來顯示網頁上的所有廣告。
使用這個 API 時,請注意下列事項:
使用這個 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: boolean | true 可強制在 SafeFrame 中顯示網頁上的所有廣告,而 false 則可將先前的設定變更為 false。如果先前未指定,將此值設為 false 不會造成任何變化。 |
傳回 | |
---|---|
PubAdsService | 系統呼叫函式的服務物件。 |
setLocation
setLocation(address: string): PubAdsService
傳送網站的地理位置資訊,方便您將委刊項指定至特定地點。
- 範例
JavaScript
// Postal code: googletag.pubads().setLocation("10001,US");
JavaScript (舊版)
// Postal code: googletag.pubads().setLocation("10001,US");
TypeScript
// Postal code: googletag.pubads().setLocation("10001,US");
參數 | |
---|---|
address: string | 任意形式的地址。 |
傳回 | |
---|---|
PubAdsService | 呼叫方法的服務物件。 |
setPrivacySettings
setPrivacySettings(privacySettings: PrivacySettingsConfig): PubAdsService
允許使用設定物件,從單一 API 設定所有隱私權設定。
- 範例
JavaScript
googletag.pubads().setPrivacySettings({ restrictDataProcessing: true, }); // Set multiple privacy settings at the same time. googletag.pubads().setPrivacySettings({ childDirectedTreatment: true, underAgeOfConsent: true, }); // Clear the configuration for childDirectedTreatment. googletag.pubads().setPrivacySettings({ childDirectedTreatment: null, });
JavaScript (舊版)
googletag.pubads().setPrivacySettings({ restrictDataProcessing: true, }); // Set multiple privacy settings at the same time. googletag.pubads().setPrivacySettings({ childDirectedTreatment: true, underAgeOfConsent: true, }); // Clear the configuration for childDirectedTreatment. googletag.pubads().setPrivacySettings({ childDirectedTreatment: null, });
TypeScript
googletag.pubads().setPrivacySettings({ restrictDataProcessing: true, }); // Set multiple privacy settings at the same time. googletag.pubads().setPrivacySettings({ childDirectedTreatment: true, underAgeOfConsent: true, }); // Clear the configuration for childDirectedTreatment. googletag.pubads().setPrivacySettings({ childDirectedTreatment: null, });
參數 | |
---|---|
privacySettings: PrivacySettingsConfig | 包含隱私權設定設定的物件。 |
傳回 | |
---|---|
PubAdsService | 系統呼叫函式的服務物件。 |
setPublisherProvidedId
setPublisherProvidedId(ppid: string): PubAdsService
設定發布商提供的 ID 值。
- 範例
JavaScript
googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
JavaScript (舊版)
googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
TypeScript
googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
- 另請參閱
參數 | |
---|---|
ppid: string | 由發布商提供的英數字元 ID。長度必須介於 32 到 150 個字元之間。 |
傳回 | |
---|---|
PubAdsService | 呼叫方法的服務物件。 |
setSafeFrameConfig
setSafeFrameConfig(config: SafeFrameConfig): PubAdsService
設定 SafeFrame 設定的網頁層級偏好設定。系統會忽略設定物件中無法辨識的任何鍵。如果為已辨識的鍵傳遞無效值,系統會忽略整個設定。
如果指定了版位層級偏好設定,系統會覆寫這些網頁層級偏好設定。
如果指定了版位層級偏好設定,系統會覆寫這些網頁層級偏好設定。
- 範例
JavaScript
googletag.pubads().setForceSafeFrame(true); const pageConfig = { allowOverlayExpansion: true, allowPushExpansion: true, sandbox: true, }; const slotConfig = { allowOverlayExpansion: false }; googletag.pubads().setSafeFrameConfig(pageConfig); // The following slot will not allow for expansion by overlay. googletag .defineSlot("/1234567/sports", [160, 600], "div-1") .setSafeFrameConfig(slotConfig) .addService(googletag.pubads()); // The following slot will inherit the page level settings, and hence // would allow for expansion by overlay. googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads()); googletag.display("div-1"); googletag.display("div-2");
JavaScript (舊版)
googletag.pubads().setForceSafeFrame(true); var pageConfig = { allowOverlayExpansion: true, allowPushExpansion: true, sandbox: true, }; var slotConfig = { allowOverlayExpansion: false }; googletag.pubads().setSafeFrameConfig(pageConfig); // The following slot will not allow for expansion by overlay. googletag .defineSlot("/1234567/sports", [160, 600], "div-1") .setSafeFrameConfig(slotConfig) .addService(googletag.pubads()); // The following slot will inherit the page level settings, and hence // would allow for expansion by overlay. googletag.defineSlot("/1234567/news", [160, 600], "div-2").addService(googletag.pubads()); googletag.display("div-1"); googletag.display("div-2");
TypeScript
googletag.pubads().setForceSafeFrame(true); const pageConfig = { allowOverlayExpansion: true, allowPushExpansion: true, sandbox: true, }; const slotConfig = { allowOverlayExpansion: false }; googletag.pubads().setSafeFrameConfig(pageConfig); // The following slot will not allow for expansion by overlay. googletag .defineSlot("/1234567/sports", [160, 600], "div-1")! .setSafeFrameConfig(slotConfig) .addService(googletag.pubads()); // The following slot will inherit the page level settings, and hence // would allow for expansion by overlay. googletag.defineSlot("/1234567/news", [160, 600], "div-2")!.addService(googletag.pubads()); googletag.display("div-1"); googletag.display("div-2");
參數 | |
---|---|
config: SafeFrameConfig | 設定物件。 |
傳回 | |
---|---|
PubAdsService | 呼叫方法的服務物件。 |
setTargeting
setTargeting(key: string, value: string | string[]): PubAdsService
為特定鍵設定自訂指定目標參數,適用於所有發布商廣告服務廣告版位。如果針對同一個鍵多次呼叫此方法,系統會覆寫舊值。這些鍵是在 Google Ad Manager 帳戶中定義。
- 範例
JavaScript
// Example with a single value for a key. googletag.pubads().setTargeting("interests", "sports"); // Example with multiple values for a key inside in an array. googletag.pubads().setTargeting("interests", ["sports", "music"]);
JavaScript (舊版)
// Example with a single value for a key. googletag.pubads().setTargeting("interests", "sports"); // Example with multiple values for a key inside in an array. googletag.pubads().setTargeting("interests", ["sports", "music"]);
TypeScript
// Example with a single value for a key. googletag.pubads().setTargeting("interests", "sports"); // Example with multiple values for a key inside in an array. googletag.pubads().setTargeting("interests", ["sports", "music"]);
- 另請參閱
參數 | |
---|---|
key: string | 指定目標參數鍵。 |
value: string | string[] | 指定目標參數值或值陣列。 |
傳回 | |
---|---|
PubAdsService | 呼叫方法的服務物件。 |
setVideoContent
setVideoContent(videoContentId: string, videoCmsId: string): void
設定要與廣告請求一併傳送的影片內容資訊,以便指定目標和排除內容。呼叫這個方法時,系統會自動啟用影片廣告。針對
videoContentId
和 videoCmsId
,請使用提供給 Google Ad Manager 內容攝入服務的值。- 另請參閱
參數 | |
---|---|
videoContentId: string | 影片內容 ID。 |
videoCmsId: string | 影片的 CMS ID。 |
updateCorrelator
updateCorrelator(): PubAdsService
變更隨廣告請求傳送的關聯器,有效地開始新的網頁瀏覽。同一個網頁檢視的所有廣告請求都會使用相同的 Correlator,而不同網頁檢視的 Correlator 則各不相同。僅適用於非同步模式。
注意:這不會影響 GPT 的長時間有效的網頁瀏覽次數,因為這項資訊會自動反映網頁上的實際廣告,且沒有到期時間。
注意:這不會影響 GPT 的長時間有效的網頁瀏覽次數,因為這項資訊會自動反映網頁上的實際廣告,且沒有到期時間。
- 範例
JavaScript
// Assume that the correlator is currently 12345. All ad requests made // by this page will currently use that value. // Replace the current correlator with a new correlator. googletag.pubads().updateCorrelator(); // The correlator will now be a new randomly selected value, different // from 12345. All subsequent ad requests made by this page will use // the new value.
JavaScript (舊版)
// Assume that the correlator is currently 12345. All ad requests made // by this page will currently use that value. // Replace the current correlator with a new correlator. googletag.pubads().updateCorrelator(); // The correlator will now be a new randomly selected value, different // from 12345. All subsequent ad requests made by this page will use // the new value.
TypeScript
// Assume that the correlator is currently 12345. All ad requests made // by this page will currently use that value. // Replace the current correlator with a new correlator. googletag.pubads().updateCorrelator(); // The correlator will now be a new randomly selected value, different // from 12345. All subsequent ad requests made by this page will use // the new value.
傳回 | |
---|---|
PubAdsService | 系統呼叫函式的服務物件。 |
googletag.ResponseInformation
代表單一廣告回應的物件。
屬性 | |
---|---|
advertiser | 廣告主的 ID。 |
campaign | 廣告活動 ID。 |
creative | 廣告素材 ID。 |
creative | 廣告的範本 ID。 |
line | 商品項目的 ID。 |
屬性
advertiserId
advertiserId: null | number
campaignId
campaignId: null | number
creativeId
creativeId: null | number
creativeTemplateId
creativeTemplateId: null | number
lineItemId
lineItemId: null | number
googletag.RewardedPayload
代表與獎勵廣告相關聯的獎勵物件
屬性 | |
---|---|
amount | 獎勵內含的商品數量。 |
type | 獎勵中包含的項目類型 (例如「硬幣」)。 |
- 另請參閱
屬性
金額
amount: number
type
type: string
googletag.SafeFrameConfig
SafeFrame 容器的設定物件。
屬性 | |
---|---|
allow | 是否允許 SafeFrame 透過疊加網頁內容,讓廣告內容擴大。 |
allow | 是否允許 SafeFrame 透過推送網頁內容,讓廣告內容展開。 |
sandbox | 是否要使用 HTML5 sandbox 屬性,在沒有使用者互動情況下,防止頂層導覽。 |
use | 已淘汰。 SafeFrame 是否應為預訂廣告素材使用隨機子網域。 |
屬性
Optional
allowOverlayExpansion
allowOverlayExpansion?: boolean
Optional
allowPushExpansion
allowPushExpansion?: boolean
Optional
sandbox
sandbox?: boolean
true
(無法強制設為 false
)。請注意,沙箱屬性會停用外掛程式 (例如 Flash)。Optional
useUniqueDomain
useUniqueDomain?: null | boolean
null
即可清除儲存的值。注意:這項功能預設為啟用。
googletag.Service
包含所有服務通用方法的基礎服務類別。
方法 | |
---|---|
add | 註冊事件監聽器,讓您在網頁上發生特定 GPT 事件時,設定及呼叫 JavaScript 函式。 |
get | 取得與這項服務相關的空檔清單。 |
remove | 移除先前註冊的事件監聽器。 |
方法
addEventListener
addEventListener<K extends keyof EventTypeMap>(eventType: K, listener: ((arg: EventTypeMap[K]) => void)): Service
註冊監聽器,讓您在網頁上發生特定 GPT 事件時,設定及呼叫 JavaScript 函式。支援下列事件:
- events.GameManualInterstitialSlotClosedEvent
- events.GameManualInterstitialSlotReadyEvent
- events.ImpressionViewableEvent
- events.RewardedSlotClosedEvent
- events.RewardedSlotGrantedEvent
- events.RewardedSlotReadyEvent
- events.SlotOnloadEvent
- events.SlotRenderEndedEvent
- events.SlotRequestedEvent
- events.SlotResponseReceived
- events.SlotVisibilityChangedEvent
- 範例
JavaScript
// 1. Adding an event listener for the PubAdsService. googletag.pubads().addEventListener("slotOnload", (event) => { console.log("Slot has been loaded:"); console.log(event); }); // 2. Adding an event listener with slot specific logic. // Listeners operate at service level, which means that you cannot add // a listener for an event for a specific slot only. You can, however, // programmatically filter a listener to respond only to a certain ad // slot, using this pattern: const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", (event) => { if (event.slot === targetSlot) { // Slot specific logic. } });
JavaScript (舊版)
// 1. Adding an event listener for the PubAdsService. googletag.pubads().addEventListener("slotOnload", function (event) { console.log("Slot has been loaded:"); console.log(event); }); // 2. Adding an event listener with slot specific logic. // Listeners operate at service level, which means that you cannot add // a listener for an event for a specific slot only. You can, however, // programmatically filter a listener to respond only to a certain ad // slot, using this pattern: var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", function (event) { if (event.slot === targetSlot) { // Slot specific logic. } });
TypeScript
// 1. Adding an event listener for the PubAdsService. googletag.pubads().addEventListener("slotOnload", (event) => { console.log("Slot has been loaded:"); console.log(event); }); // 2. Adding an event listener with slot specific logic. // Listeners operate at service level, which means that you cannot add // a listener for an event for a specific slot only. You can, however, // programmatically filter a listener to respond only to a certain ad // slot, using this pattern: const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", (event) => { if (event.slot === targetSlot) { // Slot specific logic. } });
- 另請參閱
參數 | |
---|---|
eventType: K | 字串,代表 GPT 產生的事件類型。事件類型會區分大小寫。 |
listener: ((arg: EventTypeMap[K]) => void) | 使用單一事件物件引數的函式。 |
傳回 | |
---|---|
Service | 呼叫方法的服務物件。 |
getSlots
removeEventListener
removeEventListener<K extends keyof EventTypeMap>(eventType: K, listener: ((event: EventTypeMap[K]) => void)): void
移除先前註冊的事件監聽器。
- 範例
JavaScript
googletag.cmd.push(() => { // Define a new ad slot. googletag.defineSlot("/6355419/Travel", [728, 90], "div-for-slot").addService(googletag.pubads()); // Define a new function that removes itself via removeEventListener // after the impressionViewable event fires. const onViewableListener = (event) => { googletag.pubads().removeEventListener("impressionViewable", onViewableListener); setTimeout(() => { googletag.pubads().refresh([event.slot]); }, 30000); }; // Add onViewableListener as a listener for impressionViewable events. googletag.pubads().addEventListener("impressionViewable", onViewableListener); googletag.enableServices(); });
JavaScript (舊版)
googletag.cmd.push(function () { // Define a new ad slot. googletag.defineSlot("/6355419/Travel", [728, 90], "div-for-slot").addService(googletag.pubads()); // Define a new function that removes itself via removeEventListener // after the impressionViewable event fires. var onViewableListener = function (event) { googletag.pubads().removeEventListener("impressionViewable", onViewableListener); setTimeout(function () { googletag.pubads().refresh([event.slot]); }, 30000); }; // Add onViewableListener as a listener for impressionViewable events. googletag.pubads().addEventListener("impressionViewable", onViewableListener); googletag.enableServices(); });
TypeScript
googletag.cmd.push(() => { // Define a new ad slot. googletag .defineSlot("/6355419/Travel", [728, 90], "div-for-slot")! .addService(googletag.pubads()); // Define a new function that removes itself via removeEventListener // after the impressionViewable event fires. const onViewableListener = (event: googletag.events.ImpressionViewableEvent) => { googletag.pubads().removeEventListener("impressionViewable", onViewableListener); setTimeout(() => { googletag.pubads().refresh([event.slot]); }, 30000); }; // Add onViewableListener as a listener for impressionViewable events. googletag.pubads().addEventListener("impressionViewable", onViewableListener); googletag.enableServices(); });
參數 | |
---|---|
eventType: K | 字串,代表 GPT 產生的事件類型。事件類型會區分大小寫。 |
listener: ((event: EventTypeMap[K]) => void) | 使用單一事件物件引數的函式。 |
googletag.SizeMappingBuilder
大小對應規格物件的建構工具。這個建構工具可協助您輕鬆建構尺寸規格。
方法 | |
---|---|
add | 新增從單一尺寸陣列 (代表可視區域) 到單一或多種尺寸陣列 (代表版位) 的對應項目。 |
build | 根據新增至此建構工具的對應項目,建立大小對應規格。 |
- 另請參閱
方法
addSize
addSize(viewportSize: SingleSizeArray, slotSize: GeneralSize): SizeMappingBuilder
新增從單一尺寸陣列 (代表可視區域) 到單一或多尺寸陣列 (代表版位) 的對應關係。
- 範例
JavaScript
// Mapping 1 googletag .sizeMapping() .addSize([1024, 768], [970, 250]) .addSize([980, 690], [728, 90]) .addSize([640, 480], "fluid") .addSize([0, 0], [88, 31]) // All viewports < 640x480 .build(); // Mapping 2 googletag .sizeMapping() .addSize([1024, 768], [970, 250]) .addSize([980, 690], []) .addSize([640, 480], [120, 60]) .addSize([0, 0], []) .build(); // Mapping 2 will not show any ads for the following viewport sizes: // [1024, 768] > size >= [980, 690] and // [640, 480] > size >= [0, 0]
JavaScript (舊版)
// Mapping 1 googletag .sizeMapping() .addSize([1024, 768], [970, 250]) .addSize([980, 690], [728, 90]) .addSize([640, 480], "fluid") .addSize([0, 0], [88, 31]) // All viewports < 640x480 .build(); // Mapping 2 googletag .sizeMapping() .addSize([1024, 768], [970, 250]) .addSize([980, 690], []) .addSize([640, 480], [120, 60]) .addSize([0, 0], []) .build(); // Mapping 2 will not show any ads for the following viewport sizes: // [1024, 768] > size >= [980, 690] and // [640, 480] > size >= [0, 0]
TypeScript
// Mapping 1 googletag .sizeMapping() .addSize([1024, 768], [970, 250]) .addSize([980, 690], [728, 90]) .addSize([640, 480], "fluid") .addSize([0, 0], [88, 31]) // All viewports < 640x480 .build(); // Mapping 2 googletag .sizeMapping() .addSize([1024, 768], [970, 250]) .addSize([980, 690], []) .addSize([640, 480], [120, 60]) .addSize([0, 0], []) .build(); // Mapping 2 will not show any ads for the following viewport sizes: // [1024, 768] > size >= [980, 690] and // [640, 480] > size >= [0, 0]
參數 | |
---|---|
viewportSize: SingleSizeArray | 此對應項目的可視區域大小。 |
slotSize: GeneralSize | 此對應項目的資料片段大小。 |
傳回 | |
---|---|
SizeMappingBuilder | 此建構工具的參照。 |
build
build(): null | SizeMappingArray
根據新增至此建構工具的對應項目,建構大小對應規格。
如果提供任何無效的對應項目,這個方法會傳回
注意:呼叫此方法後,建構工具的行為未定義。
如果提供任何無效的對應項目,這個方法會傳回
null
。否則,它會以正確的格式傳回規格,以便傳遞至 Slot.defineSizeMapping。注意:呼叫此方法後,建構工具的行為未定義。
傳回 | |
---|---|
null | SizeMappingArray | 這個建構工具建構的結果。如果提供的大小對應無效,則可為空值。 |
googletag.Slot
版位是代表網頁上單一廣告版位的物件。
方法 | |
---|---|
add | |
clear | 清除這個版位所有版位層級的廣告類別排除標籤。 |
clear | 清除這個版位的特定或所有自訂版位層級指定目標參數。 |
define | 為這個版位設定從可視區域大小下限到版位大小的對應陣列。 |
get | 傳回與此版位指定鍵相關聯的 AdSense 屬性值。 |
get | 傳回廣告單元的完整路徑,包括聯播網代碼和廣告單元路徑。 |
get | 傳回在這個時段設定的屬性鍵清單。 |
get | 傳回這個版位的廣告類別排除標籤。 |
get | 傳回廣告回應資訊。 |
get | 傳回在定義時提供的空格 div ID。 |
get | 傳回這個版位上的特定自訂指定參數組合。 |
get | 傳回在這個版位上設定的所有自訂指定目標鍵清單。 |
set | 為這個廣告版位設定 AdSense 屬性值。 |
set | 為這個版位設定版位層級廣告類別排除標籤。 |
set | 設定點擊網址,使用者點按廣告後會重新導向至該網址。 |
set | 設定在廣告版位中沒有廣告時,是否應隱藏該廣告版位 div 。 |
set | 設定這個版位的一般設定選項。 |
set | 設定是否應強制使用 SafeFrame 容器來顯示這個版位中的廣告。 |
set | 設定 SafeFrame 設定的版位層級偏好設定。 |
set | 為這個版位設定自訂指定目標參數。 |
update | 根據 JSON 物件中的鍵/值對應,為這個版位設定自訂指定目標參數。 |
方法
addService
addService(service: Service): Slot
將服務新增至這個版位。
- 範例
JavaScript
googletag.defineSlot("/1234567/sports", [160, 600], "div").addService(googletag.pubads());
JavaScript (舊版)
googletag.defineSlot("/1234567/sports", [160, 600], "div").addService(googletag.pubads());
TypeScript
googletag.defineSlot("/1234567/sports", [160, 600], "div")!.addService(googletag.pubads());
參數 | |
---|---|
service: Service | 要新增的服務。 |
傳回 | |
---|---|
Slot | 呼叫方法的空格物件。 |
clearCategoryExclusions
clearCategoryExclusions(): Slot
清除這個版位中的所有版位層級廣告類別排除標籤。
- 範例
JavaScript
// Set category exclusion to exclude ads with 'AirlineAd' labels. const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .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.
- 另請參閱
參數 | |
---|---|
| 指定目標參數鍵。這個鍵為選用項目,如果未指定,系統會清除所有指定目標參數。 |
傳回 | |
---|---|
Slot | 呼叫方法的空格物件。 |
defineSizeMapping
defineSizeMapping(sizeMapping: SizeMappingArray): Slot
為這個版位設定從可視區域大小下限到版位大小的對應陣列。
- 範例
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); const mapping = googletag .sizeMapping() .addSize([100, 100], [88, 31]) .addSize( [320, 400], [ [320, 50], [300, 50], ], ) .build(); slot.defineSizeMapping(mapping);
JavaScript (舊版)
var slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); var mapping = googletag .sizeMapping() .addSize([100, 100], [88, 31]) .addSize( [320, 400], [ [320, 50], [300, 50], ], ) .build(); slot.defineSizeMapping(mapping);
TypeScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div")! .addService(googletag.pubads()); const mapping = googletag .sizeMapping() .addSize([100, 100], [88, 31]) .addSize( [320, 400], [ [320, 50], [300, 50], ], ) .build(); slot.defineSizeMapping(mapping!);
- 另請參閱
參數 | |
---|---|
sizeMapping: SizeMappingArray | 大小對應項目的陣列。您可以使用 SizeMappingBuilder 建立此類型。每個大小對應項目都是兩個元素的陣列:SingleSizeArray 和 GeneralSize。 |
傳回 | |
---|---|
Slot | 呼叫方法的空格物件。 |
get
get(key: string): 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 屬性值。這會覆寫服務層級為此鍵所設定的任何值。
如果針對同一個鍵呼叫這個方法的次數超過一次,則會覆寫先前為該鍵所設定的值。必須先設定所有值,才能呼叫
如果針對同一個鍵呼叫這個方法的次數超過一次,則會覆寫先前為該鍵所設定的值。必須先設定所有值,才能呼叫
display
或 refresh
。- 範例
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 要求。
即使點擊網址已取代,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 | 是否在未傳回廣告時收合版位。 |
| 即使在擷取廣告前,是否也要收合版位。如果折疊不是 true ,則會遭到忽略。 |
傳回 | |
---|---|
Slot | 呼叫方法的空格物件。 |
setConfig
setConfig(slotConfig: SlotSettingsConfig): void
設定這個版位的一般設定選項。
參數 | |
---|---|
slotConfig: SlotSettingsConfig | 設定物件。 |
setForceSafeFrame
setForceSafeFrame(forceSafeFrame: boolean): Slot
設定是否應強制使用 SafeFrame 容器來顯示這個版位中的廣告。
使用這個 API 時,請留意下列事項:
使用這個 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: boolean | true 可強制在 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: { | 指定目標參數鍵值對應。 |
傳回 | |
---|---|
Slot | 呼叫方法的空格物件。 |
googletag.config
網頁層級設定的主要設定介面。
介面 | |
---|---|
Ad | 控制廣告展開功能的設定。 |
Component | 代表裝置端廣告競價中單一元件競價的物件。 |
Interstitial | 定義單一插播式廣告版位行為的物件。 |
Page | 網頁層級設定的主要設定介面。 |
Privacy | 用於控制發布商隱私權處理方式的設定。 |
Publisher | 發布商提供的信號 (PPS) 設定物件。 |
Slot | 用於設定時段層級的設定介面。 |
Taxonomy | 包含單一分類方式值的物件。 |
型別別名 | |
---|---|
Interstitial | 支援的插頁式廣告觸發條件。 |
Privacy | 支援的發布商隱私權處理方式。 |
Taxonomy | 發布商提供的信號 (PPS) 支援的分類。 |
型別別名
InterstitialTrigger
InterstitialTrigger: "unhideWindow" | "navBar"
PrivacyTreatment
PrivacyTreatment: "disablePersonalization"
分類
Taxonomy: "IAB_AUDIENCE_1_1" | "IAB_CONTENT_2_2"
googletag.config.AdExpansionConfig
控制廣告展開功能的設定。
屬性 | |
---|---|
enabled | 是否已啟用廣告展開功能。 |
- 範例
JavaScript
// Enable ad slot expansion across the entire page. googletag.setConfig({ adExpansion: { enabled: true }, });
JavaScript (舊版)
// Enable ad slot expansion across the entire page. googletag.setConfig({ adExpansion: { enabled: true }, });
TypeScript
// Enable ad slot expansion across the entire page. googletag.setConfig({ adExpansion: { enabled: true }, });
屬性
Optional
已啟用
enabled?: null | boolean
設定這個值會覆寫 Google Ad Manager 中預設的設定。
googletag.config.ComponentAuctionConfig
代表裝置端廣告競價中單一元件競價的物件。
屬性 | |
---|---|
auction | 這個元件競價的競價設定物件。 |
config | 與此元件競價相關聯的設定鍵。 |
屬性
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
定義單一插播式廣告版位行為的物件。
屬性 | |
---|---|
require | 是否需要取得本機儲存空間同意聲明,才能放送這則插頁式廣告。 |
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 類型中的欄位。
範例:
可透過單一 API 呼叫設定多項功能。
下方列出的所有屬性均為示例,並未反映實際使用 setConfig 的功能。如需功能組合,請參閱下方 PageSettingsConfig 類型中的欄位。
範例:
- 系統只會修改 googletag.setConfig 呼叫中指定的功能。
// Configure feature alpha. googletag.setConfig({ alpha: {...} }); // Configure feature bravo. Feature alpha is unchanged. googletag.setConfig({ bravo: {...} });
- 每次呼叫 googletag.setConfig 時,系統都會更新特定功能的所有設定。
// Configure feature charlie to echo = 1, foxtrot = true. googletag.setConfig({ charlie: { echo: 1, foxtrot: true, } }); // Update feature charlie to echo = 2. Since foxtrot was not specified, // the value is cleared. googletag.setConfig({ charlie: { echo: 2 } });
- 您可以傳遞
null
,清除功能的所有設定。// Configure features delta, golf, and hotel. googletag.setConfig({ delta: {...}, golf: {...}, hotel: {...}, }); // Feature delta and hotel are cleared, but feature golf remains set. googletag.setConfig({ delta: null, hotel: null, });
屬性 | |
---|---|
ad | 控制廣告展開功能的設定。 |
ad | 已淘汰 。 |
pps | 用於控制發布商提供的信號 (PPS) 的設定。 |
privacy | 用於控制發布商隱私權處理方式的設定。 |
thread | 設定用於控管 GPT 在算繪廣告素材時是否應產生 JS 執行緒。 |
屬性
Optional
adExpansion
adExpansion?: null | AdExpansionConfig
Optional
adYield
adYield?: null | "DISABLED" | "ENABLED_ALL_SLOTS"
Optional
pps
pps?: null | PublisherProvidedSignalsConfig
Optional
privacyTreatments
privacyTreatments?: null | PrivacyTreatmentsConfig
Optional
threadYield
threadYield?: null | "DISABLED" | "ENABLED_ALL_SLOTS"
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 類型中的欄位。
範例:
可透過單一 API 呼叫為單一時段設定多項功能。
下方列出的所有屬性均為示例,並未反映實際使用 setConfig 的功能。如需功能組合,請參閱下方 SlotSettingsConfig 類型中的欄位。
範例:
- 系統只會修改 Slot.setConfig 呼叫中指定的功能。
const slot = googletag.defineSlot("/1234567/example", [160, 600]); // Configure feature alpha. slot.setConfig({ alpha: {...} }); // Configure feature bravo. Feature alpha is unchanged. slot.setConfig({ bravo: {...} });
- 每次呼叫 Slot.setConfig 時,系統都會更新特定功能的所有設定。
// Configure feature charlie to echo = 1, foxtrot = true. slot.setConfig({ charlie: { echo: 1, foxtrot: true, } }); // Update feature charlie to echo = 2. Since foxtrot was not specified, // the value is cleared. slot.setConfig({ charlie: { echo: 2 } });
- 您可以傳遞
null
,清除功能的所有設定。// Configure features delta, golf, and hotel. slot.setConfig({ delta: {...}, golf: {...}, hotel: {...}, }); // Feature delta and hotel are cleared, but feature golf remains set. slot.setConfig({ delta: null, hotel: null, });
屬性 | |
---|---|
ad | 控制廣告展開功能的設定。 |
component | 裝置端廣告競價中要納入的元件競價陣列。 |
interstitial | 控制插頁式廣告版位行為的設定。 |
屬性
Optional
adExpansion
adExpansion?: null | AdExpansionConfig
Optional
componentAuction
componentAuction?: null | ComponentAuctionConfig[]
Optional
interstitial
interstitial?: null | InterstitialConfig
googletag.config.TaxonomyData
包含單一分類方式值的物件。
屬性 | |
---|---|
values | Taxonomy 值清單。 |
屬性
值
values: string[]
googletag.enums
這是 GPT 用於列舉類型的命名空間。
列舉 | |
---|---|
Out | GPT 支援的非頁內廣告格式。 |
Traffic | GPT 支援的流量來源。 |
列舉
OutOfPageFormat
TrafficSource
googletag.events
這是 GPT 用於事件的命名空間。程式碼可以使用 Service.addEventListener 回應這些事件。
介面 | |
---|---|
Event | 所有 GPT 事件的基本介面。 |
Event | 這是一個偽類型,可將事件名稱對應至 Service.addEventListener 和 Service.removeEventListener 的對應事件物件類型。 |
Game | 使用者關閉遊戲手動插頁式廣告時,系統會觸發這項事件。 |
Game | 當手動插頁式遊戲廣告版位已可向使用者顯示時,系統會觸發此事件。 |
Impression | 當曝光符合 Active View 標準時,系統就會觸發此事件。 |
Rewarded | 使用者關閉獎勵廣告版位時,系統會觸發這個事件。 |
Rewarded | 使用者觀看獎勵廣告後獲得獎勵時,系統會觸發這項事件。 |
Rewarded | 當獎勵廣告準備好顯示時,系統會觸發此事件。 |
Slot | 廣告素材的 iframe 觸發載入事件時,會觸發此事件。 |
Slot | 廣告素材程式碼插入版位時,系統會觸發此事件。 |
Slot | 系統為特定版位要求廣告時,就會觸發這個事件。 |
Slot | 系統收到特定版位的廣告回應時,就會觸發這項事件。 |
Slot | 廣告版位區域在畫面上的百分比發生變化時,系統就會觸發這個事件。 |
googletag.events.Event
所有 GPT 事件的基本介面。下方所有 GPT 事件都會包含下列欄位。
屬性 | |
---|---|
service | 觸發事件的服務名稱。 |
slot | 觸發事件的時間間隔。 |
- 另請參閱
屬性
serviceName
serviceName: string
slot
slot: Slot
googletag.events.EventTypeMap
這是一個偽類型,可將事件名稱對應至 Service.addEventListener 和 Service.removeEventListener 的對應事件物件類型。這項資訊僅供參考和型別安全性用途。
屬性
gameManualInterstitialSlotClosed
gameManualInterstitialSlotClosed: GameManualInterstitialSlotClosedEvent
gameManualInterstitialSlotReady
gameManualInterstitialSlotReady: GameManualInterstitialSlotReadyEvent
impressionViewable
impressionViewable: ImpressionViewableEvent
rewardedSlotClosed
rewardedSlotClosed: RewardedSlotClosedEvent
rewardedSlotGranted
rewardedSlotGranted: RewardedSlotGrantedEvent
rewardedSlotReady
rewardedSlotReady: RewardedSlotReadyEvent
slotOnload
slotOnload: SlotOnloadEvent
slotRenderEnded
slotRenderEnded: SlotRenderEndedEvent
slotRequested
slotRequested: SlotRequestedEvent
slotResponseReceived
slotResponseReceived: SlotResponseReceived
slotVisibilityChanged
slotVisibilityChanged: SlotVisibilityChangedEvent
googletag.events.GameManualInterstitialSlotClosedEvent
擴充屬性 | |
---|---|
service | 觸發事件的服務名稱。 沿用自 |
slot | 觸發事件的時間間隔。 沿用自 |
- 範例
JavaScript
// This listener is called when a game manual interstitial slot is closed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotClosed", (event) => { const slot = event.slot; console.log("Game manual interstital slot", slot.getSlotElementId(), "is closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (舊版)
// This listener is called when a game manual interstitial slot is closed. var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotClosed", function (event) { var slot = event.slot; console.log("Game manual interstital slot", slot.getSlotElementId(), "is closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
// This listener is called when a game manual interstitial slot is closed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotClosed", (event) => { const slot = event.slot; console.log("Game manual interstital slot", slot.getSlotElementId(), "is closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
- 另請參閱
googletag.events.GameManualInterstitialSlotReadyEvent
擴充屬性 | |
---|---|
service | 觸發事件的服務名稱。 沿用自 |
slot | 觸發事件的時間間隔。 沿用自 |
方法 | |
---|---|
make | 向使用者顯示手動插頁式遊戲廣告。 |
- 範例
JavaScript
// This listener is called when a game manual interstitial slot is ready to // be displayed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotReady", (event) => { const slot = event.slot; console.log( "Game manual interstital slot", slot.getSlotElementId(), "is ready to be displayed.", ); // Replace with custom logic. const displayGmiAd = true; if (displayGmiAd) { event.makeGameManualInterstitialVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (舊版)
// This listener is called when a game manual interstitial slot is ready to // be displayed. var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotReady", function (event) { var slot = event.slot; console.log( "Game manual interstital slot", slot.getSlotElementId(), "is ready to be displayed.", ); // Replace with custom logic. var displayGmiAd = true; if (displayGmiAd) { event.makeGameManualInterstitialVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
// This listener is called when a game manual interstitial slot is ready to // be displayed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotReady", (event) => { const slot = event.slot; console.log( "Game manual interstital slot", slot.getSlotElementId(), "is ready to be displayed.", ); // Replace with custom logic. const displayGmiAd = true; if (displayGmiAd) { event.makeGameManualInterstitialVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
- 另請參閱
方法
makeGameManualInterstitialVisible
makeGameManualInterstitialVisible(): void
向使用者顯示手動插頁式遊戲廣告。
googletag.events.ImpressionViewableEvent
擴充當曝光符合 Active View 標準時,系統就會觸發此事件。
屬性 | |
---|---|
service | 觸發事件的服務名稱。 沿用自 |
slot | 觸發事件的時間間隔。 沿用自 |
- 範例
JavaScript
// This listener is called when an impression becomes viewable. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("impressionViewable", (event) => { const slot = event.slot; console.log("Impression for slot", slot.getSlotElementId(), "became viewable."); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (舊版)
// This listener is called when an impression becomes viewable. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("impressionViewable", function (event) { var slot = event.slot; console.log("Impression for slot", slot.getSlotElementId(), "became viewable."); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called when an impression becomes viewable. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("impressionViewable", (event) => { const slot = event.slot; console.log("Impression for slot", slot.getSlotElementId(), "became viewable."); if (slot === targetSlot) { // Slot specific logic. } });
- 另請參閱
googletag.events.RewardedSlotClosedEvent
擴充使用者關閉獎勵廣告版位時,系統會觸發這個事件。這項事件可能會在獎勵授予前或後觸發。如要判斷是否已授予獎勵,請改用 events.RewardedSlotGrantedEvent。
屬性 | |
---|---|
service | 觸發事件的服務名稱。 沿用自 |
slot | 觸發事件的時間間隔。 沿用自 |
- 範例
JavaScript
const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called when the user closes a rewarded ad slot. googletag.pubads().addEventListener("rewardedSlotClosed", (event) => { const slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "has been closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (舊版)
var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called when the user closes a rewarded ad slot. googletag.pubads().addEventListener("rewardedSlotClosed", function (event) { var slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "has been closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called when the user closes a rewarded ad slot. googletag.pubads().addEventListener("rewardedSlotClosed", (event) => { const slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "has been closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
googletag.events.RewardedSlotGrantedEvent
擴充使用者觀看獎勵廣告後獲得獎勵時,系統會觸發此事件。如果使用者在符合獎勵條件前關閉廣告,系統就不會觸發這項事件。
屬性 | |
---|---|
payload | 包含已授予獎勵資訊的物件。 |
service | 觸發事件的服務名稱。 沿用自 |
slot | 觸發事件的時間間隔。 沿用自 |
- 範例
JavaScript
const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotGranted", (event) => { const slot = event.slot; console.group("Reward granted for slot", slot.getSlotElementId(), "."); // Log details of the reward. console.log("Reward type:", event.payload?.type); console.log("Reward amount:", event.payload?.amount); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (舊版)
var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotGranted", function (event) { var _a, _b; var slot = event.slot; console.group("Reward granted for slot", slot.getSlotElementId(), "."); // Log details of the reward. console.log("Reward type:", (_a = event.payload) === null || _a === void 0 ? void 0 : _a.type); console.log( "Reward amount:", (_b = event.payload) === null || _b === void 0 ? void 0 : _b.amount, ); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotGranted", (event) => { const slot = event.slot; console.group("Reward granted for slot", slot.getSlotElementId(), "."); // Log details of the reward. console.log("Reward type:", event.payload?.type); console.log("Reward amount:", event.payload?.amount); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } }); }
屬性
payload
payload: null | RewardedPayload
googletag.events.RewardedSlotReadyEvent
擴充當獎勵廣告準備好顯示時,系統會觸發此事件。發布商必須負責在顯示廣告前,向使用者提供觀看廣告的選項。
屬性 | |
---|---|
service | 觸發事件的服務名稱。 沿用自 |
slot | 觸發事件的時間間隔。 沿用自 |
方法 | |
---|---|
make | 顯示獎勵廣告。 |
- 範例
JavaScript
// This listener is called when a rewarded ad slot becomes ready to be // displayed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotReady", (event) => { const slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed."); // Replace with custom logic. const userHasConsented = true; if (userHasConsented) { event.makeRewardedVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (舊版)
// This listener is called when a rewarded ad slot becomes ready to be // displayed. var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotReady", function (event) { var slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed."); // Replace with custom logic. var userHasConsented = true; if (userHasConsented) { event.makeRewardedVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
// This listener is called when a rewarded ad slot becomes ready to be // displayed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotReady", (event) => { const slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed."); // Replace with custom logic. const userHasConsented = true; if (userHasConsented) { event.makeRewardedVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
方法
makeRewardedVisible
makeRewardedVisible(): void
顯示獎勵廣告。使用者必須同意觀看廣告,才能呼叫這個方法。
googletag.events.SlotOnloadEvent
擴充廣告素材的 iframe 觸發載入事件時,系統會觸發此事件。在同步顯示模式中顯示多媒體廣告時,系統不會使用 iframe,因此不會觸發
SlotOnloadEvent
。屬性 | |
---|---|
service | 觸發事件的服務名稱。 沿用自 |
slot | 觸發事件的時間間隔。 沿用自 |
- 範例
JavaScript
// This listener is called when a creative iframe load event fires. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", (event) => { const slot = event.slot; console.log("Creative iframe for slot", slot.getSlotElementId(), "has loaded."); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (舊版)
// This listener is called when a creative iframe load event fires. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", function (event) { var slot = event.slot; console.log("Creative iframe for slot", slot.getSlotElementId(), "has loaded."); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called when a creative iframe load event fires. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotOnload", (event) => { const slot = event.slot; console.log("Creative iframe for slot", slot.getSlotElementId(), "has loaded."); if (slot === targetSlot) { // Slot specific logic. } });
- 另請參閱
googletag.events.SlotRenderEndedEvent
擴充廣告素材程式碼插入廣告位時,系統會觸發此事件。這個事件會在擷取廣告素材資源之前發生,因此廣告素材可能還未顯示。如果您需要瞭解版位所有廣告素材資源何時載入完成,請改用 events.SlotOnloadEvent。
屬性 | |
---|---|
advertiser | 已算繪的廣告廣告主 ID。 |
campaign | 已轉譯廣告的廣告活動 ID。 |
company | 對顯示的候補廣告出價的公司 ID。 |
creative | 已顯示的預留廣告廣告素材 ID。 |
creative | 已算繪的預留廣告廣告素材範本 ID。 |
is | 廣告是否為候補廣告。 |
is | 是否已為版位傳回廣告。 |
label | 已淘汰 。 |
line | 已算繪的預訂廣告委刊項 ID。 |
service | 觸發事件的服務名稱。 沿用自 |
size | 表示算繪廣告素材的像素大小。 |
slot | 觸發事件的時間間隔。 沿用自 |
slot | 是否已使用算繪廣告變更版位內容。 |
source | 已算入保留空間或候補廣告的廣告素材 ID。 |
source | 已算入預訂或候補廣告的委刊項 ID。 |
yield | 顯示的回補廣告收益群組 ID。 |
- 範例
JavaScript
// This listener is called when a slot has finished rendering. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRenderEnded", (event) => { const slot = event.slot; console.group("Slot", slot.getSlotElementId(), "finished rendering."); // Log details of the rendered ad. console.log("Advertiser ID:", event.advertiserId); console.log("Campaign ID:", event.campaignId); console.log("Company IDs:", event.companyIds); console.log("Creative ID:", event.creativeId); console.log("Creative Template ID:", event.creativeTemplateId); console.log("Is backfill?:", event.isBackfill); console.log("Is empty?:", event.isEmpty); console.log("Line Item ID:", event.lineItemId); console.log("Size:", event.size); console.log("Slot content changed?", event.slotContentChanged); console.log("Source Agnostic Creative ID:", event.sourceAgnosticCreativeId); console.log("Source Agnostic Line Item ID:", event.sourceAgnosticLineItemId); console.log("Yield Group IDs:", event.yieldGroupIds); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (舊版)
// This listener is called when a slot has finished rendering. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRenderEnded", function (event) { var slot = event.slot; console.group("Slot", slot.getSlotElementId(), "finished rendering."); // Log details of the rendered ad. console.log("Advertiser ID:", event.advertiserId); console.log("Campaign ID:", event.campaignId); console.log("Company IDs:", event.companyIds); console.log("Creative ID:", event.creativeId); console.log("Creative Template ID:", event.creativeTemplateId); console.log("Is backfill?:", event.isBackfill); console.log("Is empty?:", event.isEmpty); console.log("Line Item ID:", event.lineItemId); console.log("Size:", event.size); console.log("Slot content changed?", event.slotContentChanged); console.log("Source Agnostic Creative ID:", event.sourceAgnosticCreativeId); console.log("Source Agnostic Line Item ID:", event.sourceAgnosticLineItemId); console.log("Yield Group IDs:", event.yieldGroupIds); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called when a slot has finished rendering. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRenderEnded", (event) => { const slot = event.slot; console.group("Slot", slot.getSlotElementId(), "finished rendering."); // Log details of the rendered ad. console.log("Advertiser ID:", event.advertiserId); console.log("Campaign ID:", event.campaignId); console.log("Company IDs:", event.companyIds); console.log("Creative ID:", event.creativeId); console.log("Creative Template ID:", event.creativeTemplateId); console.log("Is backfill?:", event.isBackfill); console.log("Is empty?:", event.isEmpty); console.log("Line Item ID:", event.lineItemId); console.log("Size:", event.size); console.log("Slot content changed?", event.slotContentChanged); console.log("Source Agnostic Creative ID:", event.sourceAgnosticCreativeId); console.log("Source Agnostic Line Item ID:", event.sourceAgnosticLineItemId); console.log("Yield Group IDs:", event.yieldGroupIds); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
- 另請參閱
屬性
advertiserId
campaignId
companyIds
creativeId
creativeTemplateId
creativeTemplateId: null | number
null
。isBackfill
isBackfill: boolean
true
,否則為 false
。isEmpty
isEmpty: boolean
true
,否則為 false
。labelIds
labelIds: null | number[]
lineItemId
size
size: null | string | number[]
[728, 90]
。空廣告版位的值為 null
。slotContentChanged
slotContentChanged: boolean
true
;否則為 false
。sourceAgnosticCreativeId
sourceAgnosticCreativeId: null | number
null
。sourceAgnosticLineItemId
sourceAgnosticLineItemId: null | number
null
。yieldGroupIds
googletag.events.SlotRequestedEvent
擴充系統為特定版位要求廣告時,就會觸發這項事件。
屬性 | |
---|---|
service | 觸發事件的服務名稱。 沿用自 |
slot | 觸發事件的時間間隔。 沿用自 |
- 範例
JavaScript
// This listener is called when the specified service issues an ad // request for a slot. Each slot will fire this event, even though they // may be batched together in a single request if single request // architecture (SRA) is enabled. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRequested", (event) => { const slot = event.slot; console.log("Slot", slot.getSlotElementId(), "has been requested."); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (舊版)
// This listener is called when the specified service issues an ad // request for a slot. Each slot will fire this event, even though they // may be batched together in a single request if single request // architecture (SRA) is enabled. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRequested", function (event) { var slot = event.slot; console.log("Slot", slot.getSlotElementId(), "has been requested."); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called when the specified service issues an ad // request for a slot. Each slot will fire this event, even though they // may be batched together in a single request if single request // architecture (SRA) is enabled. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRequested", (event) => { const slot = event.slot; console.log("Slot", slot.getSlotElementId(), "has been requested."); if (slot === targetSlot) { // Slot specific logic. } });
- 另請參閱
googletag.events.SlotResponseReceived
擴充系統收到特定版位的廣告回應時,就會觸發這項事件。
屬性 | |
---|---|
service | 觸發事件的服務名稱。 沿用自 |
slot | 觸發事件的時間間隔。 沿用自 |
- 範例
JavaScript
// This listener is called when an ad response has been received // for a slot. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotResponseReceived", (event) => { const slot = event.slot; console.log("Ad response for slot", slot.getSlotElementId(), "received."); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (舊版)
// This listener is called when an ad response has been received // for a slot. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotResponseReceived", function (event) { var slot = event.slot; console.log("Ad response for slot", slot.getSlotElementId(), "received."); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called when an ad response has been received // for a slot. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotResponseReceived", (event) => { const slot = event.slot; console.log("Ad response for slot", slot.getSlotElementId(), "received."); if (slot === targetSlot) { // Slot specific logic. } });
- 另請參閱
googletag.events.SlotVisibilityChangedEvent
擴充廣告版位區域在畫面上的百分比發生變化時,系統就會觸發這個事件。事件會受到節流限制,每 200 毫秒最多只會觸發一次。
屬性 | |
---|---|
in | 可見廣告區域的百分比。 |
service | 觸發事件的服務名稱。 沿用自 |
slot | 觸發事件的時間間隔。 沿用自 |
- 範例
JavaScript
// This listener is called whenever the on-screen percentage of an // ad slot's area changes. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotVisibilityChanged", (event) => { const slot = event.slot; console.group("Visibility of slot", slot.getSlotElementId(), "changed."); // Log details of the event. console.log("Visible area:", `${event.inViewPercentage}%`); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (舊版)
// This listener is called whenever the on-screen percentage of an // ad slot's area changes. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotVisibilityChanged", function (event) { var slot = event.slot; console.group("Visibility of slot", slot.getSlotElementId(), "changed."); // Log details of the event. console.log("Visible area:", "".concat(event.inViewPercentage, "%")); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called whenever the on-screen percentage of an // ad slot's area changes. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotVisibilityChanged", (event) => { const slot = event.slot; console.group("Visibility of slot", slot.getSlotElementId(), "changed."); // Log details of the event. console.log("Visible area:", `${event.inViewPercentage}%`); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
- 另請參閱
屬性
inViewPercentage
inViewPercentage: number
googletag.secureSignals
這是 GPT 用於管理安全信號的命名空間。
介面 | |
---|---|
Bidder | 傳回特定出價方的安全信號。 |
Publisher | 傳回特定發布商的安全信號。 |
Secure | 用於管理安全信號的介面。 |
型別別名 | |
---|---|
Secure | 針對特定出價方或供應商傳回安全信號的介面。 |
型別別名
SecureSignalProvider
SecureSignalProvider: BidderSignalProvider | PublisherSignalProvider
id
或 networkCode
其中一個,但不能兩者都提供。googletag.secureSignals.BidderSignalProvider
針對特定出價方傳回安全信號。
出價方安全信號供應器包含 2 個部分:
出價方安全信號供應器包含 2 個部分:
- 收集器函式,會傳回可解析為安全信號的
Promise
。 id
:用於識別與信號相關聯的出價方。
屬性 | |
---|---|
collector | 這個函式會傳回 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
googletag.secureSignals.PublisherSignalProvider
傳回特定發布商的安全信號。
發布商信號供應者包含 2 個部分:
發布商信號供應者包含 2 個部分:
- 收集器函式,會傳回可解析為安全信號的
Promise
。 networkCode
:識別與信號相關聯的發布商。
屬性 | |
---|---|
collector | 這個函式會傳回 Promise ,並解析為安全信號。 |
network | 與這個安全信號相關聯的發布商網路代碼 (可在廣告單元路徑中看到)。 |
- 範例
JavaScript
// networkCode is provided googletag.secureSignalProviders.push({ networkCode: "123456", collectorFunction: () => { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
JavaScript (舊版)
// networkCode is provided googletag.secureSignalProviders.push({ networkCode: "123456", collectorFunction: function () { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
TypeScript
// networkCode is provided googletag.secureSignalProviders!.push({ networkCode: "123456", collectorFunction: () => { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
- 另請參閱
屬性
collectorFunction
collectorFunction: (() => Promise<string>)
Promise
,並解析為安全信號。networkCode
networkCode: string
googletag.secureSignals.SecureSignalProvidersArray
用於管理安全信號的介面。
方法 | |
---|---|
clear | 從快取中清除所有收集器的信號。 |
push | 將新的 secureSignals.SecureSignalProvider 新增至信號供應器陣列,並開始信號產生程序。 |
方法
clearAllCache
clearAllCache(): void
從快取中清除所有收集器的信號。
呼叫這個方法可能會降低信號納入目前和未來網頁瀏覽的廣告請求的可能性。因此,只有在發生有意義的狀態變更時,才應呼叫此方法,例如表示新使用者的事件 (登入、登出、註冊等)。
呼叫這個方法可能會降低信號納入目前和未來網頁瀏覽的廣告請求的可能性。因此,只有在發生有意義的狀態變更時,才應呼叫此方法,例如表示新使用者的事件 (登入、登出、註冊等)。
push
push(provider: SecureSignalProvider): void
將新的 secureSignals.SecureSignalProvider 新增至信號供應器陣列,並開始信號產生程序。
參數 | |
---|---|
provider: SecureSignalProvider | 要新增至陣列的 secureSignals.SecureSignalProvider 物件。 |