GPT 參考資料

這項參考資料會使用 TypeScript 標記法描述類型。下表提供簡要說明。

類型運算式
string 原始字串類型。
string[] 一種陣列類型,其中值只能是字串。
number | string 聯集類型,其中值可以是數字或字串。
Array<number | string> 陣列類型,其中值屬於複雜 (聯集) 類型。
[number, string] 元組類型,其中值是必須包含數字和字串的雙元素陣列。
Slot 物件類型,其中值是 googletag.Slot 的例項。
() => void 沒有已定義引數,且沒有回傳值的函式類型。

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

類型註解

變數、參數名稱、屬性名稱或函式簽名之後的冒號代表類型註解。類型註解會說明半形冒號左側的元素可接受或回傳的元素類型。下表列出您可能會在這項參考資料中看到的註解類型範例。

輸入註解
param: string 表示 param 接受或傳回字串值。這個語法可用於變數、參數、屬性和傳回類型。
param?: number | string 表示 param 為選用項目,但如果有指定,則接受數字或字串。這個語法會用於參數和屬性。
...params: Array<() => void> 表示 params 是可接受函式的 rest 參數 。其餘參數接受指定類型的值數量沒有限制。


類型定義

類型
SingleSize | MultiSize

用於版位的有效尺寸設定,可以是一或多種大小。

SingleSize[]

單一有效大小的清單。

"fluid" | ["fluid"]

版位可設定的命名大小。在大部分的情況下,尺寸是固定大小的矩形,但在某些情況下,我們需要其他種類的尺寸規格。只有以下項目是有效的已命名大小:

  • fluid:廣告容器會取用上層 div 的 100% 寬度,然後配合廣告素材內容調整高度。類似於網頁上一般區塊元素的行為。用於原生廣告 (請參閱相關文章)。請注意,fluid['fluid'] 都是可接受的表單,將版位大小宣告為自動調整大小。

SingleSizeArray | NamedSize

版位的單一有效大小。

[number, number]

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

[SingleSizeArray, GeneralSize]

可視區域大小與廣告大小的對應。用於回應式廣告。

SizeMapping[]

尺寸對應清單。

"unhideWindow" | "navBar"

支援的插頁式廣告觸發條件。

"disablePersonalization"

支援的發布商隱私權處理方式。

"IAB_AUDIENCE_1_1" | "IAB_CONTENT_2_2"

發布商提供的信號 (PPS) 支援的分類。

BidderSignalProvider | PublisherSignalProvider

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

列舉類型

列舉
googletag.enums.OutOfPageFormat
GPT 支援的非頁內廣告格式。
googletag.enums.TrafficSource
GPT 支援的流量來源


googletag.enums.OutOfPageFormat

  • GPT 支援的非頁內廣告格式。

  • 另請參閱
  • BOTTOM_ANCHOR
    這個錨定格式是版位固定在可視區域底部的錨定格式。
    INTERSTITIAL
    網站插頁式廣告素材格式。
    LEFT_SIDE_RAIL
    左側邊欄格式。
    REWARDED
    獎勵格式。
    RIGHT_SIDE_RAIL
    右側邊欄格式。
    TOP_ANCHOR
    這個錨定格式是版位固定在可視區域頂端的錨定格式。


googletag.enums.TrafficSource


googletag

Google 發布商廣告代碼 API 所用的全域命名空間。

變數摘要
apiReady
標記表示 GPT API 已載入並隨時可以呼叫。
cmd
GPT 相關呼叫非同步執行作業的全域指令佇列參照。
pubadsReady
此標記表示 PubAdsService 已啟用、已載入且可完全正常運作。
secureSignalProviders
安全信號提供者陣列的參照。
函式摘要
companionAds
傳回 CompanionAdsService 的參照。
defineOutOfPageSlot
使用指定廣告單元路徑建構非頁內廣告版位。
defineSlot
使用指定廣告單元路徑和大小建置廣告版位,並將該版位與要置入廣告的網頁上 div 元素 ID 建立關聯。
destroySlots
刪除指定的版位,從 GPT 移除所有相關物件和參照。
disablePublisherConsole
停用 Google 發布商控制台。
display
指示運算單元服務轉譯該運算單元。
enableServices
啟用網頁中廣告版位已定義的所有 GPT 服務。
getVersion
傳回最新版本的 GPT。
openConsole
開啟 Google 發布商控制台。
pubads
傳回 PubAdsService 的參照。
setAdIframeTitle
設定從現在開始為所有 PubAdsService 建立的廣告容器 iframe 的標題。
setConfig
設定網頁的一般設定選項。
sizeMapping
建立新的 SizeMappingBuilder


googletagapiReady

  • apiReady: boolean | undefined
  • 標記表示 GPT API 已載入並準備就緒,可以呼叫。在 API 準備就緒之前,這個屬性會改為 undefined

    請注意,處理非同步的建議方法是使用 googletag.cmd 將回呼排入佇列,以待 GPT 就緒。這些回呼不需要檢查 googletag.apiReady,因為這些回呼會在 API 設定後保證執行。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


googletagcmd

  • cmd: Array<(this: typeof globalThis) => void> | CommandArray
  • 用於執行 GPT 相關呼叫非同步執行作業的全域指令佇列。

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


googletagpubadsReady

  • pubadsReady: boolean | undefined
  • 此標記表示 PubAdsService 已啟用、已載入且可完全正常運作。這個屬性只會是 undefined,直到呼叫 enableServices 並載入及初始化 PubAdsService 為止。


googletagsecureSignalProviders

  • secureSignalProviders: SecureSignalProvider[] | SecureSignalProvidersArray | undefined
  • 安全信號提供者陣列的參照。

    安全信號提供者陣列接受一系列信號產生函式,並依序叫用這些函式。此模式是用來取代標準陣列,此陣列用於將信號產生函式排入佇列,以便在載入 GPT 後叫用。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


googletagcompanionAds


googletagdefineOutOfPageSlot

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

    如果是自訂非頁內廣告,div 是要包含廣告的 div 元素 ID。詳情請參閱非頁內廣告素材一文。

    對於 GPT 管理的非頁內廣告,divOutOfPageFormat 支援。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    // Define a custom out-of-page ad slot.
    googletag.defineOutOfPageSlot("/1234567/sports", "div-1");
    
    // Define a GPT managed web interstitial ad slot.
    googletag.defineOutOfPageSlot("/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL);
    
    另請參閱
  • 參數
    adUnitPath: string
    包含聯播網代碼和廣告單元代碼的完整廣告單元路徑
    div?: string | OutOfPageFormat
    要包含這個廣告單元或 OutOfPageFormat 的 div 編號。
  • 傳回
    Slot | null
    新建立的運算單元;如果無法建立時段,則為 null


googletagdefineSlot

  • defineSlot(adUnitPath: string, size: GeneralSize, div?: string): Slot | null
  • 使用指定廣告單元路徑和大小建置廣告版位,並將該版位與要置入廣告的網頁上 div 元素 ID 建立關聯。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


googletagdestroySlots

  • destroySlots(slots?: Slot[]): boolean
  • 刪除指定的版位,從 GPT 移除所有相關物件和參照。這個 API 不支援回傳式曝光版位和隨播廣告版位。

    若在版位上呼叫這個 API,系統會清除廣告,並從 GPT 維護的內部狀態移除版位物件。在運算單元物件上呼叫更多函式,會導致未定義的行為。請注意,如果發布商頁面維護了與該版位相關的參照,瀏覽器可能仍會釋出與該版位相關的記憶體。呼叫這個 API 即可重複使用與該版位相關聯的 div。

    具體來說,如果刪除廣告版位,系統就會在 GPT 的長效網頁瀏覽機制中移除廣告,因此日後的請求不會受到影響,也不會因與這則廣告有關的路障型廣告或競爭排除條件影響。如果在從網頁中移除版位的 div 之前未呼叫這個函式,將導致未定義的行為。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    // The calls to construct an ad and display contents.
    const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!;
    googletag.display("div-1");
    const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!;
    googletag.display("div-2");
    
    // This call to destroy only slot1.
    googletag.destroySlots([slot1]);
    
    // This call to destroy both slot1 and slot2.
    googletag.destroySlots([slot1, slot2]);
    
    // This call to destroy all slots.
    googletag.destroySlots();
    
  • 參數
    slots?: Slot[]
    要刪除的版位陣列。陣列是選用項目;如未指定任何運算單元,系統會刪除該陣列。
  • 傳回
    boolean
    如果版位已刪除,則為 true,否則為 false


googletagdisablePublisherConsole


googletagdisplay

  • display(divOrSlot: string | Element | Slot): void
  • 指示運算單元服務轉譯運算單元。每個廣告版位在每個網頁上只能顯示一次。所有版位都必須定義完畢,並與某個服務建立關聯,才能顯示在網頁上。元素必須先出現在 DOM 中,才能發出顯示呼叫。要達成這個目標,一般做法是將程式碼放在方法呼叫中命名的 div 元素中。

    如果使用單一請求架構 (SRA),系統會在呼叫此方法時,同時擷取所有未擷取的廣告版位。若要強制廣告版位不顯示,您必須移除整個 div。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    googletag.cmd.push(() => {
      googletag.display("div-1");
    });
    
    另請參閱
  • 參數
    divOrSlot: string | Element | Slot
    包含廣告版位或 div 元素的 div 元素 ID,或是版位物件。如要提供 div 元素,則該元素的「id」屬性必須與傳入 defineSlot 的 ID 相符。


googletagenableServices

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


googletaggetVersion

  • getVersion(): string
  • 傳回最新版本的 GPT。

  • 另請參閱
  • 傳回
    string
    目前正在執行的 GPT 版本字串。


googletagopenConsole

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

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    // Calling with div ID.
    googletag.openConsole("div-1");
    
    // Calling without div ID.
    googletag.openConsole();
    
    另請參閱
  • 參數
    div?: string
    廣告版位 div ID。這是選用值。如有提供,發布商控制台會嘗試開啟並顯示指定廣告版位的詳細資料。


googletagpubads


googletagsetAdIframeTitle

  • setAdIframeTitle(title: string): void
  • 從現在開始,為 PubAdsService 建立的所有廣告容器 iframe 設定標題。

  • 範例

    JavaScript

    googletag.setAdIframeTitle("title");
    

    JavaScript (舊版)

    googletag.setAdIframeTitle("title");
    

    TypeScript

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


googletagsetConfig


googletagsizeMapping


googletagCommandArray

指令陣列會接受一連串函式,並依序叫用這些函式。它是用來取代標準陣列,該陣列會在載入 GPT 後將函式排入佇列。

方法摘要
push
依序執行引數中指定的函式序列。


push

  • push(...f: Array<(this: typeof globalThis) => void>): number
  • 依序執行引數中指定的函式序列。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


googletagCompanionAdsService

擴充 Service

隨播廣告服務。影片廣告會使用這項服務顯示隨播廣告。

方法摘要
addEventListener
註冊一個監聽器,讓您可以在頁面上發生特定 GPT 事件時,設定及呼叫 JavaScript 函式。
getSlots
取得與這項服務相關聯的運算單元清單。
removeEventListener
移除先前註冊的事件監聽器。
setRefreshUnfilledSlots
設定是否要自動補上尚未供應廣告的隨播廣告版位。
另請參閱


setRefreshUnfilledSlots

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

    您可以在頁面生命週期內多次呼叫這個方法,藉此開啟或關閉候補廣告。系統只會針對也向 PubAdsService 註冊的版位進行補充作業。基於政策限制,這種方法不適用於在 Ad Exchange 影片放送時,填入空白的隨播廣告版位。

  • 範例

    JavaScript

    googletag.companionAds().setRefreshUnfilledSlots(true);
    

    JavaScript (舊版)

    googletag.companionAds().setRefreshUnfilledSlots(true);
    

    TypeScript

    googletag.companionAds().setRefreshUnfilledSlots(true);
    
  • 參數
    value: boolean
    true:自動填入未填入廣告的版位,false 則保持不變。


googletagPrivacySettingsConfig

隱私權設定的設定物件。

資源摘要
childDirectedTreatment
limitedAds
配合發布商的法規遵循需求,在受限制的廣告模式下放送。
nonPersonalizedAds
有助於在非個人化廣告模式下放送,協助符合發布商的法規需求。
restrictDataProcessing
可在受限的處理模式下放送廣告,滿足發布商的法規遵循需求。
trafficSource
指出請求代表的是購買或自然流量。
underAgeOfConsent
指出是否要將廣告請求標為未滿規定年齡的使用者。
另請參閱


childDirectedTreatment


limitedAds

  • limitedAds: boolean
  • 採用受限制的廣告模式放送,以符合發布商法規遵循需求。

    您可以透過下列兩種方式指示 GPT 請求受限制的廣告:

    受限制的廣告網址載入 GPT 時,才能手動設定受限制的廣告。如果嘗試從標準網址載入 GPT 時嘗試修改這項設定,會產生發布商控制台警告

    請注意,使用 CMP 時,不需要手動啟用受限制的廣告。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


nonPersonalizedAds

  • nonPersonalizedAds: boolean
  • 讓廣告在非個人化廣告模式下放送,以符合發布商的法規遵循需求。


restrictDataProcessing

  • restrictDataProcessing: boolean
  • 讓廣告在受限的處理模式下放送,以滿足發布商的法規遵循需求。


trafficSource

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

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


underAgeOfConsent

  • underAgeOfConsent: null | boolean
  • 指出是否要將廣告請求標為未滿規定年齡的使用者。如要清除設定,請設為 null


googletagPubAdsService

擴充 Service

發布商廣告服務。這項服務是用來從您的 Google Ad Manager 帳戶擷取及顯示廣告。

方法摘要
addEventListener
註冊一個監聽器,讓您可以在頁面上發生特定 GPT 事件時,設定及呼叫 JavaScript 函式。
clear
從指定的版位移除廣告,並以空白內容取代。
clearCategoryExclusions
清除所有網頁層級廣告類別排除標籤。
clearTargeting
清除特定鍵或所有鍵的自訂指定參數。
collapseEmptyDivs
啟用版位 div 的收合功能,這樣在沒有可顯示的廣告內容時,就不會佔用網頁上的任何空間。
disableInitialLoad
停用網頁載入時的廣告請求,但允許透過 PubAdsService.refresh 呼叫請求廣告。
display
根據指定廣告單元路徑和大小建構並顯示廣告版位。
enableLazyLoad
依據設定物件定義,在 GPT 中啟用延遲載入功能。
enableSingleRequest
啟用單一請求模式,以便同時擷取多則廣告。
enableVideoAds
告知 GPT 這個網頁上將會顯示影片廣告。
get
傳回與指定鍵相關聯的 AdSense 屬性值。
getAttributeKeys
傳回已在這項服務中設定的屬性鍵。
getSlots
取得與這項服務相關聯的運算單元清單。
getTargeting
傳回已設定的自訂服務層級指定參數。
getTargetingKeys
傳回已設定的自訂服務層級指定鍵清單。
isInitialLoadDisabled
傳回先前 PubAdsService.disableInitialLoad 呼叫是否成功停用廣告的初始請求。
refresh
擷取並顯示網頁上特定或所有版位的新廣告。
removeEventListener
移除先前註冊的事件監聽器。
set
設定 AdSense 屬性值,這些屬性值會套用到「發布商廣告」服務下的所有廣告版位。
setCategoryExclusion
針對特定標籤名稱設定網頁層級廣告類別排除條件。
setCentering
啟用及停用廣告水平置中功能。
setForceSafeFrame
設定是否應使用 SafeFrame 容器顯示網頁上的所有廣告。
setLocation
傳送網站的位置資訊,方便您將委刊項指定到特定位置。
setPrivacySettings
允許使用設定物件,透過單一 API 設定所有隱私權設定。
setPublisherProvidedId
設定發布商提供的 ID 值。
setSafeFrameConfig
設定 SafeFrame 設定的網頁層級偏好設定。
setTargeting
設定適用於所有發布商廣告服務廣告版位的特定鍵自訂指定參數。
setVideoContent
設定要與廣告請求一起傳送的影片內容資訊,做為指定目標和排除內容的依據。
updateCorrelator
變更與廣告請求一起傳送的 Correlator,可有效啟動新的網頁瀏覽。


clear

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

    具體來說,清除廣告版位後,廣告就會從 GPT 的長效網頁瀏覽中移除,因此日後的請求不會受到影響,也不會有與這則廣告有關的路障型廣告或競爭排除項目影響。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!;
    googletag.display("div-1");
    const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!;
    googletag.display("div-2");
    
    // This call to clear only slot1.
    googletag.pubads().clear([slot1]);
    
    // This call to clear both slot1 and slot2.
    googletag.pubads().clear([slot1, slot2]);
    
    // This call to clear all slots.
    googletag.pubads().clear();
    
  • 參數
    slots?: Slot[]
    要清除的運算單元陣列。陣列是選用項目,如未指定任何版位,系統會清除所有版位。
  • 傳回
    boolean
    如果已清除版位,則傳回 true,否則傳回 false


clearCategoryExclusions

  • clearCategoryExclusions(): PubAdsService
  • 清除所有網頁層級廣告類別排除標籤。如果您想重新整理版位,這個方法就能派上用場。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    // Set category exclusion to exclude ads with 'AirlineAd' labels.
    googletag.pubads().setCategoryExclusion("AirlineAd");
    
    // Make ad requests. No ad with 'AirlineAd' label will be returned.
    
    // Clear category exclusions so all ads can be returned.
    googletag.pubads().clearCategoryExclusions();
    
    // Make ad requests. Any ad can be returned.
    
    另請參閱
  • 傳回
    PubAdsService
    呼叫該方法的服務物件。


clearTargeting

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

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    googletag.pubads().setTargeting("interests", "sports");
    googletag.pubads().setTargeting("colors", "blue");
    googletag.pubads().setTargeting("fruits", "apple");
    
    googletag.pubads().clearTargeting("interests");
    // Targeting 'colors' and 'fruits' are still present, while 'interests'
    // was cleared.
    
    googletag.pubads().clearTargeting();
    // All targeting has been cleared.
    
    另請參閱
  • 參數
    key?: string
    指定參數鍵。鍵為選填項目;如未指定,系統會清除所有指定目標參數。
  • 傳回
    PubAdsService
    呼叫該方法的服務物件。


collapseEmptyDivs

  • collapseEmptyDivs(collapseBeforeAdFetch?: boolean): boolean
  • 啟用版位 div 的收合功能,這樣在沒有可顯示的廣告時,就不會佔用網頁上的任何空間。您必須先設定這個模式,才能啟用服務。

  • 另請參閱
  • 參數
    collapseBeforeAdFetch?: boolean
    是否在系統擷取廣告之前收合版位。這是選用參數;如未提供,系統會使用 false 做為預設值。
  • 傳回
    boolean
    如果 div 收合模式已啟用,則傳回 true;如果因為在服務啟用後呼叫該方法,而無法啟用收合模式,則傳回 false


disableInitialLoad


display

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

    注意:呼叫此方法時,系統會建立版位和網頁狀態的快照,確保在傳送廣告請求及顯示回應時,能夠維持一致性。在呼叫這個方法後,對版位或網頁狀態所做的任何變更 (包括指定目標、隱私權設定、強制使用 SafeFrame 等),只會套用到後續的 display()refresh() 要求。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


enableLazyLoad

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

    注意:只有在所有版位都不在擷取邊界內時,才能在 SRA 中延遲擷取。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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

      我們以可視區域大小 (百分比) 的方式擷取廣告時,版位與目前可視區域之間的最短距離。0 值表示「版位進入可視區域時」,100 表示「廣告距離 1 個可視區域離開時」,以此類推。
    • renderMarginPercent

      廣告版位與目前可視區域之間的最短距離,我們才會顯示廣告。這樣做可以預先擷取廣告,但目前仍在等待顯示及下載其他子資源。這個值的運作方式與可視區域的百分比相同:fetchMarginPercent
    • mobileScaling

      為行動裝置利潤套用的調節係數。這讓行動裝置和電腦的邊距各有不同。舉例來說,如果值為 2.0,系統會將行動裝置的所有邊界乘以 2,進而增加版位在擷取及算繪前的最短距離。


enableSingleRequest

  • enableSingleRequest(): boolean
  • 啟用單一請求模式,以便同時擷取多則廣告。您必須先定義所有發布商廣告版位並新增至 PubAdsService,才能啟用服務。您必須先設定單一要求模式,才能啟用服務。

  • 另請參閱
  • 傳回
    boolean
    如果啟用單一要求模式,則傳回 true;如果無法啟用單一要求模式,則傳回 false (因為在服務啟用後呼叫該方法)。


enableVideoAds

  • enableVideoAds(): void
  • 告知 GPT 這個網頁上將會顯示影片廣告。如此一來,即可對多媒體和影片廣告設下競爭排除限制。如果已知有影片內容,請呼叫 PubAdsService.setVideoContent,即可針對多媒體廣告使用內容排除功能。


get

  • get(key: string): null | string
  • 傳回與指定鍵相關聯的 AdSense 屬性值。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    googletag.pubads().set("adsense_background_color", "#FFFFFF");
    googletag.pubads().get("adsense_background_color");
    // Returns '#FFFFFF'.
    
    另請參閱
  • 參數
    key: string
    要尋找的屬性名稱。
  • 傳回
    null | string
    屬性索引鍵的目前值;如果沒有索引鍵,則為 null


getAttributeKeys

  • getAttributeKeys(): string[]
  • 傳回已在這項服務中設定的屬性鍵。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    googletag.pubads().set("adsense_background_color", "#FFFFFF");
    googletag.pubads().set("adsense_border_color", "#AABBCC");
    googletag.pubads().getAttributeKeys();
    // Returns ['adsense_background_color', 'adsense_border_color'].
    
  • 傳回
    string[]
    針對這項服務設定的屬性鍵陣列。順序未定義。


getTargeting

  • getTargeting(key: string): string[]
  • 傳回已設定的自訂服務層級指定參數。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    googletag.pubads().setTargeting("interests", "sports");
    
    googletag.pubads().getTargeting("interests");
    // Returns ['sports'].
    
    googletag.pubads().getTargeting("age");
    // Returns [] (empty array).
    
  • 參數
    key: string
    要尋找的指定鍵。
  • 傳回
    string[]
    與這個鍵相關聯的值;如果沒有這類鍵,則為空白陣列。


getTargetingKeys

  • getTargetingKeys(): string[]
  • 傳回已設定的自訂服務層級指定鍵清單。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    googletag.pubads().setTargeting("interests", "sports");
    googletag.pubads().setTargeting("colors", "blue");
    
    googletag.pubads().getTargetingKeys();
    // Returns ['interests', 'colors'].
    
  • 傳回
    string[]
    指定鍵陣列。順序未定義。


isInitialLoadDisabled


refresh

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

    為了讓所有瀏覽器都能正確運作,呼叫 refresh 之前必須呼叫廣告版位 display。如果省略呼叫 display,重新整理作業可能會發生非預期的行為。如有需要,您可以使用 PubAdsService.disableInitialLoad 方法停止 display 擷取廣告。

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

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    const slot1 = googletag.defineSlot("/1234567/sports", [728, 90], "div-1")!;
    googletag.display("div-1");
    const slot2 = googletag.defineSlot("/1234567/news", [160, 600], "div-2")!;
    googletag.display("div-2");
    
    // This call to refresh fetches a new ad for slot1 only.
    googletag.pubads().refresh([slot1]);
    
    // This call to refresh fetches a new ad for both slot1 and slot2.
    googletag.pubads().refresh([slot1, slot2]);
    
    // This call to refresh fetches a new ad for each slot.
    googletag.pubads().refresh();
    
    // This call to refresh fetches a new ad for slot1, without changing
    // the correlator.
    googletag.pubads().refresh([slot1], { changeCorrelator: false });
    
    // This call to refresh fetches a new ad for each slot, without
    // changing the correlator.
    googletag.pubads().refresh(null, { changeCorrelator: false });
    
    另請參閱
  • 參數
    slots?: null | Slot[]
    要重新整理的版位。陣列為選用項目,如未指定任何版位,系統會重新整理所有版位。
    options?: { changeCorrelator: boolean }
    與這個重新整理呼叫相關聯的設定選項。
    • changeCorrelator

      指定是否要為擷取廣告產生新的 Correlator。我們的廣告伺服器會暫時保留此 correlator 值 (目前為 30 秒,但隨時可能變更),因此如果接收到同一個 correlator 的要求很近,就會視為單一網頁瀏覽。根據預設,每次重新整理都會產生新的 Correlator。

      注意:這個選項不會影響 GPT 的長效網頁瀏覽,因為該頁面會自動反映目前網頁上的廣告,且沒有到期時間。


set

  • set(key: string, value: string): PubAdsService
  • 為發布商廣告服務中的所有廣告版位設定 AdSense 屬性值。

    如果針對同一個鍵重複呼叫這個方法,系統將覆寫先前為該鍵設定的值。必須先設定所有值,才能呼叫 displayrefresh

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    googletag.pubads().set("adsense_background_color", "#FFFFFF");
    
    另請參閱
  • 參數
    key: string
    屬性的名稱。
    value: string
    屬性值。
  • 傳回
    PubAdsService
    呼叫該方法的服務物件。


setCategoryExclusion

  • setCategoryExclusion(categoryExclusion: string): PubAdsService
  • 針對特定標籤名稱設定網頁層級廣告類別排除條件。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    // Label = AirlineAd.
    googletag.pubads().setCategoryExclusion("AirlineAd");
    
    另請參閱
  • 參數
    categoryExclusion: string
    要新增的廣告類別排除標籤。
  • 傳回
    PubAdsService
    呼叫該方法的服務物件。


setCentering

  • setCentering(centerAds: boolean): void
  • 啟用及停用水平置中廣告。置中設定預設為停用。在舊版 gpt_mobile.js 中,系統預設啟用置中功能。

    您必須在呼叫 displayrefresh 之前叫用這個方法,因為只有呼叫這個方法後才要求的廣告都會置中。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    // Make ads centered.
    googletag.pubads().setCentering(true);
    
  • 參數
    centerAds: boolean
    true:將廣告置中,false 可讓廣告靠左對齊。


setForceSafeFrame

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

    使用這個 API 時,請注意下列事項:

    • 這項設定只會影響個別版位提出的「後續」廣告請求。
    • 版位層級設定 (如有指定) 一律會覆寫網頁層級設定。
    • 如果設為 true (在版位層級或網頁層級),廣告一律會使用 SafeFrame 容器顯示,與在 Google Ad Manager 使用者介面中所做的選擇無關。
    • 不過,如果設為 false 或未指定,廣告將根據在 Google Ad Manager UI 中選取的廣告素材類型,使用 SafeFrame 容器顯示。
    • 使用這個 API 時請務必小心謹慎,因為這個 API 可能會影響廣告素材跳脫 iframe 或直接透過發布商網頁顯示的廣告素材行為。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    googletag.pubads().setForceSafeFrame(true);
    
    // The following slot will be opted-out of the page-level force
    // SafeFrame instruction.
    googletag
      .defineSlot("/1234567/sports", [160, 600], "div-1")!
      .setForceSafeFrame(false)
      .addService(googletag.pubads());
    
    // The following slot will have SafeFrame forced.
    googletag.defineSlot("/1234567/news", [160, 600], "div-2")!.addService(googletag.pubads());
    
    googletag.display("div-1");
    googletag.display("div-2");
    
    另請參閱
  • 參數
    forceSafeFrame: boolean
    true 可強制網頁上的所有廣告在 SafeFrame 中顯示,false 則可將先前的設定變更為 false。如未事先指定,將此值設為 false,並不會變更任何設定。
  • 傳回
    PubAdsService
    呼叫函式的服務物件。


setLocation

  • setLocation(address: string): PubAdsService
  • 傳送網站的位置資訊,方便您將委刊項指定到特定位置。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


setPrivacySettings

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

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    googletag.pubads().setPrivacySettings({
      restrictDataProcessing: true,
    });
    
    // Set multiple privacy settings at the same time.
    googletag.pubads().setPrivacySettings({
      childDirectedTreatment: true,
      underAgeOfConsent: true,
    });
    
    // Clear the configuration for childDirectedTreatment.
    googletag.pubads().setPrivacySettings({
      childDirectedTreatment: null,
    });
    
    另請參閱
  • 參數
    privacySettings: PrivacySettingsConfig
    包含隱私權設定的物件。
  • 傳回
    PubAdsService
    呼叫函式的服務物件。


setPublisherProvidedId

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

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


setSafeFrameConfig

  • setSafeFrameConfig(config: SafeFrameConfig): PubAdsService
  • 設定 SafeFrame 設定的網頁層級偏好設定。系統會忽略設定物件中所有無法辨識的金鑰。如果向可識別的鍵傳遞無效值,系統會忽略整個設定。

    版位層級偏好設定將覆寫這些網頁層級偏好設定 (如有指定)。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    googletag.pubads().setForceSafeFrame(true);
    
    const pageConfig = {
      allowOverlayExpansion: true,
      allowPushExpansion: true,
      sandbox: true,
    };
    
    const slotConfig = { allowOverlayExpansion: false };
    
    googletag.pubads().setSafeFrameConfig(pageConfig);
    
    // The following slot will not allow for expansion by overlay.
    googletag
      .defineSlot("/1234567/sports", [160, 600], "div-1")!
      .setSafeFrameConfig(slotConfig)
      .addService(googletag.pubads());
    
    // The following slot will inherit the page level settings, and hence
    // would allow for expansion by overlay.
    googletag.defineSlot("/1234567/news", [160, 600], "div-2")!.addService(googletag.pubads());
    
    googletag.display("div-1");
    googletag.display("div-2");
    
    另請參閱
  • 參數
    config: SafeFrameConfig
    設定物件。
  • 傳回
    PubAdsService
    呼叫該方法的服務物件。


setTargeting

  • setTargeting(key: string, value: string | string[]): PubAdsService
  • 設定套用至所有發布商廣告服務廣告版位的特定鍵自訂指定參數。如果為同一個鍵多次呼叫這個方法,系統將覆寫舊的值。這些鍵是由您的 Google Ad Manager 帳戶定義。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    // Example with a single value for a key.
    googletag.pubads().setTargeting("interests", "sports");
    
    // Example with multiple values for a key inside in an array.
    googletag.pubads().setTargeting("interests", ["sports", "music"]);
    
    另請參閱
  • 參數
    key: string
    指定參數鍵。
    value: string | string[]
    指定參數值或值的陣列。
  • 傳回
    PubAdsService
    呼叫該方法的服務物件。


setVideoContent

  • setVideoContent(videoContentId: string, videoCmsId: string): void
  • 設定要與廣告請求一起傳送的影片內容資訊,做為指定目標和排除內容的依據。呼叫此方法後,影片廣告就會自動啟用。如果是 videoContentIdvideoCmsId,請使用提供給 Google Ad Manager 內容擷取服務的值。

  • 另請參閱
  • 參數
    videoContentId: string
    影片內容 ID。
    videoCmsId: string
    影片 CMS ID。


updateCorrelator

  • updateCorrelator(): PubAdsService
  • 變更與廣告請求一併傳送的 Correlator,有效啟動新的網頁瀏覽。對於來自一次網頁瀏覽的所有廣告請求,correlator 都相同,在所有網頁檢視中則不重複。僅適用於非同步模式。

    注意:這不會影響 GPT 的長效網頁瀏覽,因為後者會自動反映實際在網頁上的廣告,且沒有到期時間。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    // Assume that the correlator is currently 12345. All ad requests made
    // by this page will currently use that value.
    
    // Replace the current correlator with a new correlator.
    googletag.pubads().updateCorrelator();
    
    // The correlator will now be a new randomly selected value, different
    // from 12345. All subsequent ad requests made by this page will use
    // the new value.
    
  • 傳回
    PubAdsService
    呼叫函式的服務物件。


googletagResponseInformation

代表單一廣告回應的物件。

資源摘要
advertiserId
廣告客戶的 ID。
campaignId
廣告活動的 ID。
creativeId
廣告素材的 ID。
creativeTemplateId
廣告的範本 ID。
lineItemId
委刊項的 ID。
另請參閱


advertiserId

  • advertiserId: null | number
  • 廣告客戶的 ID。


campaignId

  • campaignId: null | number
  • 廣告活動的 ID。


creativeId

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


creativeTemplateId

  • creativeTemplateId: null | number
  • 廣告的範本 ID。


lineItemId

  • lineItemId: null | number
  • 委刊項的 ID。


googletagRewardedPayload

代表獎勵廣告相關獎勵的物件

資源摘要
amount
獎勵所含商品數量。
type
獎勵內含的項目類型 (例如「錢幣」)。
另請參閱


amount

  • amount: number
  • 獎勵項目的數量。


type

  • type: string
  • 獎勵內含的項目類型 (例如「錢幣」)。


googletagSafeFrameConfig

SafeFrame 容器的設定物件。

資源摘要
allowOverlayExpansion
設定 SafeFrame 是否應允許隨著網頁內容重疊而展開廣告內容。
allowPushExpansion
是否應允許 SafeFrame 透過推送網頁內容來展開廣告內容。
sandbox
SafeFrame 是否應使用 HTML5 沙箱屬性,以便在使用者沒有互動的情況下防止頂層導覽。
useUniqueDomain
已淘汰。設定 SafeFrame 是否應在預訂廣告素材中使用隨機子網域。
另請參閱


allowOverlayExpansion

  • allowOverlayExpansion: boolean
  • 設定 SafeFrame 是否應允許隨著網頁內容重疊而展開廣告內容。


allowPushExpansion

  • allowPushExpansion: boolean
  • 是否應允許 SafeFrame 透過推送網頁內容來展開廣告內容。


sandbox

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


useUniqueDomain

  • useUniqueDomain: null | boolean
  • 設定 SafeFrame 是否應在預訂廣告素材中使用隨機子網域。傳入 null 即可清除已儲存的值。

    注意:這項功能預設為啟用。

  • 另請參閱


googletagService

包含所有服務通用方法的基礎服務類別。

方法摘要
addEventListener
註冊一個監聽器,讓您可以在頁面上發生特定 GPT 事件時,設定及呼叫 JavaScript 函式。
getSlots
取得與這項服務相關聯的運算單元清單。
removeEventListener
移除先前註冊的事件監聽器。


addEventListener

  • addEventListener<K extends keyof EventTypeMap>(eventType: K, listener: (arg: EventTypeMap[K]) => void): Service
  • 註冊一個監聽器,讓您可以在頁面上發生特定 GPT 事件時,設定及呼叫 JavaScript 函式。系統支援下列事件:

    在呼叫事件監聽器時,系統會將適當事件類型的物件傳遞給事件監聽器。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


getSlots

  • getSlots(): Slot[]
  • 取得與這項服務相關聯的運算單元清單。

  • 傳回
    Slot[]
    運算單元會按照加入服務的順序。


removeEventListener

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

  • 範例

    JavaScript

    googletag.cmd.push(() => {
      // Define a new ad slot.
      googletag.defineSlot("/6355419/Travel", [728, 90], "div-for-slot").addService(googletag.pubads());
    
      // Define a new function that removes itself via removeEventListener
      // after the impressionViewable event fires.
      const onViewableListener = (event) => {
        googletag.pubads().removeEventListener("impressionViewable", onViewableListener);
        setTimeout(() => {
          googletag.pubads().refresh([event.slot]);
        }, 30000);
      };
    
      // Add onViewableListener as a listener for impressionViewable events.
      googletag.pubads().addEventListener("impressionViewable", onViewableListener);
      googletag.enableServices();
    });
    

    JavaScript (舊版)

    googletag.cmd.push(function () {
      // Define a new ad slot.
      googletag.defineSlot("/6355419/Travel", [728, 90], "div-for-slot").addService(googletag.pubads());
    
      // Define a new function that removes itself via removeEventListener
      // after the impressionViewable event fires.
      var onViewableListener = function (event) {
        googletag.pubads().removeEventListener("impressionViewable", onViewableListener);
        setTimeout(function () {
          googletag.pubads().refresh([event.slot]);
        }, 30000);
      };
    
      // Add onViewableListener as a listener for impressionViewable events.
      googletag.pubads().addEventListener("impressionViewable", onViewableListener);
      googletag.enableServices();
    });
    

    TypeScript

    googletag.cmd.push(() => {
      // Define a new ad slot.
      googletag
        .defineSlot("/6355419/Travel", [728, 90], "div-for-slot")!
        .addService(googletag.pubads());
    
      // Define a new function that removes itself via removeEventListener
      // after the impressionViewable event fires.
      const onViewableListener = (event: googletag.events.ImpressionViewableEvent) => {
        googletag.pubads().removeEventListener("impressionViewable", onViewableListener);
        setTimeout(() => {
          googletag.pubads().refresh([event.slot]);
        }, 30000);
      };
    
      // Add onViewableListener as a listener for impressionViewable events.
      googletag.pubads().addEventListener("impressionViewable", onViewableListener);
      googletag.enableServices();
    });
    
  • 參數
    eventType: K
    字串,代表 GPT 產生的事件類型。事件類型須區分大小寫;
    listener: (event: EventTypeMap[K]) => void
    採用單一事件物件引數的函式。


googletagSizeMappingBuilder

尺寸對應規格物件的建構工具。這個建構工具可協助您輕鬆建構大小規格。

方法摘要
addSize
新增單一大小陣列 (代表可視區域) 的對應關係,以及代表版位的單一或多種大小陣列。
build
根據新增至這個建構工具的對應,建立尺寸對應規格。
另請參閱


addSize

  • addSize(viewportSize: SingleSizeArray, slotSize: GeneralSize): SizeMappingBuilder
  • 新增單一大小陣列 (代表可視區域) 的對應關係,以及代表版位的單一或多種大小陣列。

  • 範例

    JavaScript

    // Mapping 1
    googletag
      .sizeMapping()
      .addSize([1024, 768], [970, 250])
      .addSize([980, 690], [728, 90])
      .addSize([640, 480], "fluid")
      .addSize([0, 0], [88, 31]) // All viewports < 640x480
      .build();
    
    // Mapping 2
    googletag
      .sizeMapping()
      .addSize([1024, 768], [970, 250])
      .addSize([980, 690], [])
      .addSize([640, 480], [120, 60])
      .addSize([0, 0], [])
      .build();
    
    // Mapping 2 will not show any ads for the following viewport sizes:
    // [1024, 768] > size >= [980, 690] and
    // [640, 480] > size >= [0, 0]
    

    JavaScript (舊版)

    // Mapping 1
    googletag
      .sizeMapping()
      .addSize([1024, 768], [970, 250])
      .addSize([980, 690], [728, 90])
      .addSize([640, 480], "fluid")
      .addSize([0, 0], [88, 31]) // All viewports < 640x480
      .build();
    
    // Mapping 2
    googletag
      .sizeMapping()
      .addSize([1024, 768], [970, 250])
      .addSize([980, 690], [])
      .addSize([640, 480], [120, 60])
      .addSize([0, 0], [])
      .build();
    
    // Mapping 2 will not show any ads for the following viewport sizes:
    // [1024, 768] > size >= [980, 690] and
    // [640, 480] > size >= [0, 0]
    

    TypeScript

    // Mapping 1
    googletag
      .sizeMapping()
      .addSize([1024, 768], [970, 250])
      .addSize([980, 690], [728, 90])
      .addSize([640, 480], "fluid")
      .addSize([0, 0], [88, 31]) // All viewports < 640x480
      .build();
    
    // Mapping 2
    googletag
      .sizeMapping()
      .addSize([1024, 768], [970, 250])
      .addSize([980, 690], [])
      .addSize([640, 480], [120, 60])
      .addSize([0, 0], [])
      .build();
    
    // Mapping 2 will not show any ads for the following viewport sizes:
    // [1024, 768] > size >= [980, 690] and
    // [640, 480] > size >= [0, 0]
    
  • 參數
    viewportSize: SingleSizeArray
    此對應項目的可視區域大小。
    slotSize: GeneralSize
    此對應項目的版位大小。
  • 傳回
    SizeMappingBuilder
    此建構工具的參照。


build

  • build(): null | SizeMappingArray
  • 根據新增至這個建構工具的對應建立尺寸對應規格。

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

    注意:呼叫此方法後,建構工具的行為未定義。

  • 傳回
    null | SizeMappingArray
    這個建構工具建構的結果。如果提供的大小對應無效,則可設為空值。


googletagSlot

版位是一種物件,代表網頁上的單一廣告版位。

方法摘要
addService
Service 新增至這個版位。
clearCategoryExclusions
清除這個版位的所有版位層級廣告類別排除標籤。
clearTargeting
清除這個版位的特定或所有自訂版位層級指定參數。
defineSizeMapping
設定這個版位的版位大小與最小可視區域大小的對應陣列。
get
傳回與此版位的指定鍵相關聯的 AdSense 屬性值。
getAdUnitPath
傳回廣告單元的完整路徑,包含聯播網代碼和廣告單元路徑。
getAttributeKeys
傳回這個版位上設定的屬性鍵清單。
getCategoryExclusions
傳回這個版位的廣告類別排除標籤。
getResponseInformation
傳回廣告回應資訊。
getSlotElementId
傳回在定義版位時提供的版位 div ID。
getTargeting
傳回針對這個版位設定的特定自訂指定參數。
getTargetingKeys
傳回此版位上設定的所有自訂指定鍵清單。
set
設定這個廣告版位的 AdSense 屬性值。
setCategoryExclusion
為這個版位設定版位層級廣告類別排除標籤。
setClickUrl
設定點擊廣告後,系統會將使用者重新導向的點擊網址。
setCollapseEmptyDiv
設定當版位沒有廣告時,是否應隱藏 div 版位。
setConfig
設定此運算單元的一般設定選項。
setForceSafeFrame
設定是否要使用 SafeFrame 容器強制顯示這個版位中的廣告。
setSafeFrameConfig
設定 SafeFrame 設定的版位層級偏好設定。
setTargeting
設定這個版位的自訂指定目標參數。
updateTargetingFromMap
從 JSON 物件中的 key:value 對應設定這個版位的自訂指定目標參數。


addService

  • addService(service: Service): Slot
  • Service 新增至這個版位。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


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.
    
    另請參閱
  • 參數
    key?: string
    指定參數鍵。鍵為選填項目;如未指定,系統會清除所有指定目標參數。
  • 傳回
    Slot
    呼叫該方法的運算單元物件。


defineSizeMapping

  • defineSizeMapping(sizeMapping: SizeMappingArray): Slot
  • 設定這個版位的版位大小下限與版位大小的對應陣列。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .addService(googletag.pubads());
    
    const mapping = googletag
      .sizeMapping()
      .addSize([100, 100], [88, 31])
      .addSize(
        [320, 400],
        [
          [320, 50],
          [300, 50],
        ]
      )
      .build();
    
    slot.defineSizeMapping(mapping!);
    
    另請參閱
  • 參數
    sizeMapping: SizeMappingArray
    大小對應陣列。您可以使用 SizeMappingBuilder 建立這個查詢。每個大小對應都是由兩個元素的陣列:SingleSizeArrayGeneralSize
  • 傳回
    Slot
    呼叫該方法的運算單元物件。


get

  • get(key: string): null | string
  • 傳回與此版位的指定鍵相關聯的 AdSense 屬性值。如要查看這個運算單元沿用的服務層級屬性,請使用 PubAdsService.get

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .set("adsense_background_color", "#FFFFFF")
      .addService(googletag.pubads());
    
    slot.get("adsense_background_color");
    // Returns '#FFFFFF'.
    
    另請參閱
  • 參數
    key: string
    要尋找的屬性名稱。
  • 傳回
    null | string
    屬性索引鍵的目前值;如果沒有索引鍵,則為 null


getAdUnitPath

  • getAdUnitPath(): string
  • 傳回廣告單元的完整路徑,包含聯播網代碼和廣告單元路徑。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .addService(googletag.pubads());
    
    slot.getAdUnitPath();
    // Returns '/1234567/sports'.
    
  • 傳回
    string
    廣告單元路徑。


getAttributeKeys

  • getAttributeKeys(): string[]
  • 傳回這個版位設定的屬性鍵清單。如要查看這個運算單元繼承的服務層級屬性金鑰,請使用 PubAdsService.getAttributeKeys

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .set("adsense_background_color", "#FFFFFF")
      .set("adsense_border_color", "#AABBCC")
      .addService(googletag.pubads());
    
    slot.getAttributeKeys();
    // Returns ['adsense_background_color', 'adsense_border_color'].
    
  • 傳回
    string[]
    屬性鍵的陣列。順序未定義。


getCategoryExclusions

  • getCategoryExclusions(): string[]
  • 傳回這個版位的廣告類別排除標籤。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .setCategoryExclusion("AirlineAd")
      .setCategoryExclusion("TrainAd")
      .addService(googletag.pubads());
    
    slot.getCategoryExclusions();
    // Returns ['AirlineAd', 'TrainAd'].
    
  • 傳回
    string[]
    這個版位的廣告類別排除標籤;如果未設定,則會提供空白陣列。


getResponseInformation

  • getResponseInformation(): null | ResponseInformation
  • 傳回廣告回應資訊。根據針對該版位的最後一個廣告回應而定。如果系統在版位沒有廣告時呼叫這個方法,會傳回 null

  • 傳回
    null | ResponseInformation
    最新的廣告回應資訊;如果版位沒有廣告,則為 null


getSlotElementId

  • getSlotElementId(): string
  • 傳回在定義版位時提供的版位 div ID。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


getTargeting

  • getTargeting(key: string): string[]
  • 傳回此版位上的某個自訂指定參數。不包含服務層級的指定目標參數。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .setTargeting("allow_expandable", "true")
      .addService(googletag.pubads());
    
    slot.getTargeting("allow_expandable");
    // Returns ['true'].
    
    slot.getTargeting("age");
    // Returns [] (empty array).
    
  • 參數
    key: string
    要尋找的指定鍵。
  • 傳回
    string[]
    與這個鍵相關聯的值;如果沒有這類鍵,則為空白陣列。


getTargetingKeys

  • getTargetingKeys(): string[]
  • 傳回此版位上設定的所有自訂指定鍵清單。不包含服務層級的指定鍵。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    const slot = googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .setTargeting("allow_expandable", "true")
      .setTargeting("interests", ["sports", "music"])
      .addService(googletag.pubads());
    
    slot.getTargetingKeys();
    // Returns ['interests', 'allow_expandable'].
    
  • 傳回
    string[]
    指定鍵陣列。順序未定義。


set

  • set(key: string, value: string): Slot
  • 設定這個廣告版位的 AdSense 屬性值。這會覆寫該鍵在服務層級設定的任何值。

    如果為同一個鍵重複呼叫這個方法,該鍵先前設定的值將遭到覆寫。必須先設定所有值,才能呼叫 displayrefresh

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    // Setting an attribute on a single ad slot.
    googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .set("adsense_background_color", "#FFFFFF")
      .addService(googletag.pubads());
    
    另請參閱
  • 參數
    key: string
    屬性的名稱。
    value: string
    屬性值。
  • 傳回
    Slot
    呼叫該方法的運算單元物件。


setCategoryExclusion

  • setCategoryExclusion(categoryExclusion: string): Slot
  • 為這個版位設定版位層級廣告類別排除標籤。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    // Label = AirlineAd
    googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .setCategoryExclusion("AirlineAd")
      .addService(googletag.pubads());
    
    另請參閱
  • 參數
    categoryExclusion: string
    要新增的廣告類別排除標籤。
  • 傳回
    Slot
    呼叫該方法的運算單元物件。


setClickUrl

  • setClickUrl(value: string): Slot
  • 設定點擊網址,系統會將點擊廣告的使用者重新導向。

    即使點擊網址已取代,Google Ad Manager 伺服器仍會記錄一次點擊。凡是與放送的廣告素材相關聯的到達網頁網址,都會附加至你提供的值。後續呼叫會覆寫這個值。這只適用於非 SRA 要求。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    googletag
      .defineSlot("/1234567/sports", [160, 600], "div")!
      .setClickUrl("http://www.example.com?original_click_url=")
      .addService(googletag.pubads());
    
  • 參數
    value: string
    要設定的點擊網址。
  • 傳回
    Slot
    呼叫該方法的運算單元物件。


setCollapseEmptyDiv

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

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    googletag
      .defineSlot("/1234567/sports", [160, 600], "div-1")!
      .setCollapseEmptyDiv(true, true)
      .addService(googletag.pubads());
    // The above will cause the div for this slot to be collapsed
    // when the page is loaded, before ads are requested.
    
    googletag
      .defineSlot("/1234567/sports", [160, 600], "div-2")!
      .setCollapseEmptyDiv(true)
      .addService(googletag.pubads());
    // The above will cause the div for this slot to be collapsed
    // only after GPT detects that no ads are available for the slot.
    
    另請參閱
  • 參數
    collapse: boolean
    是否在未傳回任何廣告時收合版位。
    collapseBeforeAdFetch?: boolean
    是否在系統擷取廣告之前收合版位。如果收合不是 true,則忽略此值。
  • 傳回
    Slot
    呼叫該方法的運算單元物件。


setConfig


setForceSafeFrame

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

    使用這個 API 時,請注意下列事項:

    • 這項設定只會影響個別版位提出的「後續」廣告請求。
    • 版位層級設定 (如有指定) 一律會覆寫網頁層級設定。
    • 如果設為 true (在版位層級或網頁層級),廣告一律會使用 SafeFrame 容器顯示,與在 Google Ad Manager 使用者介面中所做的選擇無關。
    • 不過,如果設為 false 或未指定,廣告將根據在 Google Ad Manager UI 中選取的廣告素材類型,使用 SafeFrame 容器顯示。
    • 使用這個 API 時請務必小心謹慎,因為這個 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 物件中的 key:value 對應設定這個版位的自訂指定參數。這與針對物件所有鍵/值呼叫 Slot.setTargeting 相同。您可以在 Google Ad Manager 帳戶中定義這些鍵。

    注意:

    • 如果進行覆寫,系統只會保留最後一個值。
    • 如果值是陣列,任何先前的值都會遭到覆寫,且不會合併。
    • 這裡設定的值會覆寫在服務層級設定的值。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

    const slot = googletag.defineSlot("/1234567/sports", [160, 600], "div")!;
    
    slot.updateTargetingFromMap({
      color: "red",
      interests: ["sports", "music", "movies"],
    });
    
  • 參數
    map: {  [adUnitPath: string]: string | string[] }
    指定參數鍵/值對應。
  • 傳回
    Slot
    呼叫該方法的運算單元物件。


googletag.configAdExpansionConfig

廣告展開控制項的設定。

資源摘要
enabled
是否啟用或停用廣告展開功能。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

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


enabled


googletag.configComponentAuctionConfig

代表裝置端廣告競價中單一元件競價的物件。

資源摘要
auctionConfig
此元件競價的競價設定物件。
configKey
與此元件競價相關聯的設定鍵。
另請參閱


auctionConfig

  • auctionConfig: null | { auctionSignals: unknown, decisionLogicUrl: string, interestGroupBuyers: string[], perBuyerExperimentGroupIds: {  [buyer: string]: number }, perBuyerGroupLimits: {  [buyer: string]: number }, perBuyerSignals: {  [buyer: string]: unknown }, perBuyerTimeouts: {  [buyer: string]: number }, seller: string, sellerExperimentGroupId: number, sellerSignals: unknown, sellerTimeout: number, trustedScoringSignalsUrl: string }
  • 這項元件競價的競價設定物件。

    如果將值設為 null,系統就會刪除指定configKey的任何現有設定。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


configKey

  • configKey: string
  • 與此元件競價相關聯的設定鍵。

    這個值不得空白,而且不得重複。如果兩個 ComponentAuctionConfig 物件共用相同的 configKey 值,最後設定值會覆寫先前的設定。


googletag.configInterstitialConfig

定義單一插頁式廣告版位行為的物件。

資源摘要
triggers
此插頁式廣告的插頁式廣告觸發條件設定。


triggers

  • triggers: Partial<Record<InterstitialTrigger, boolean>>
  • 這個插頁式廣告的插頁式廣告觸發條件設定。

    將插頁式廣告觸發條件的值設為 true 即可啟用,false 則會停用。這會覆寫 Google Ad Manager 中設定的預設值。

  • 範例

    JavaScript

    // Define a GPT managed web interstitial ad slot.
    const interstitialSlot = googletag.defineOutOfPageSlot(
      "/1234567/sports",
      googletag.enums.OutOfPageFormat.INTERSTITIAL
    );
    
    // Enable optional interstitial triggers.
    // Change this value to false to disable.
    const enableTriggers = true;
    
    interstitialSlot.setConfig({
      interstitial: {
        triggers: {
          navBar: enableTriggers,
          unhideWindow: enableTriggers,
        },
      },
    });
    

    JavaScript (舊版)

    // Define a GPT managed web interstitial ad slot.
    var interstitialSlot = googletag.defineOutOfPageSlot(
      "/1234567/sports",
      googletag.enums.OutOfPageFormat.INTERSTITIAL
    );
    
    // Enable optional interstitial triggers.
    // Change this value to false to disable.
    var enableTriggers = true;
    
    interstitialSlot.setConfig({
      interstitial: {
        triggers: {
          navBar: enableTriggers,
          unhideWindow: enableTriggers,
        },
      },
    });
    

    TypeScript

    // Define a GPT managed web interstitial ad slot.
    const interstitialSlot = googletag.defineOutOfPageSlot(
      "/1234567/sports",
      googletag.enums.OutOfPageFormat.INTERSTITIAL
    )!;
    
    // Enable optional interstitial triggers.
    // Change this value to false to disable.
    const enableTriggers = true;
    
    interstitialSlot.setConfig({
      interstitial: {
        triggers: {
          navBar: enableTriggers,
          unhideWindow: enableTriggers,
        },
      },
    });
    
    另請參閱


googletag.configPageSettingsConfig

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

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

下列所有屬性皆為範例,並不代表實際使用 setConfig 的功能。如需功能組合的相關資訊,請參閱下方 PageSettingsConfig 類型中的欄位。

範例:

  • 系統只會修改 setConfig 呼叫中指定的功能。
      // Configure feature alpha.
      googletag.setConfig({
          alpha: {...}
      });
    
      // Configure feature bravo. Feature alpha is unchanged.
      googletag.setConfig({
         bravo: {...}
      });
    
  • 每次呼叫 setConfig 時,特定功能的所有設定都會更新。
      // Configure feature charlie to echo = 1, foxtrot = true.
      googletag.setConfig({
          charlie: {
              echo: 1,
              foxtrot: true,
          }
      });
    
      // Update feature charlie to echo = 2. Since foxtrot was not specified,
      // the value is cleared.
      googletag.setConfig({
          charlie: {
              echo: 2
          }
      });
    
  • 如要清除功能的所有設定,請傳遞 null
      // Configure features delta, golf, and hotel.
      googletag.setConfig({
          delta: {...},
          golf: {...},
          hotel: {...},
      });
    
      // Feature delta and hotel are cleared, but feature golf remains set.
      googletag.setConfig({
          delta: null,
          hotel: null,
      });
    

資源摘要
adExpansion
廣告展開控制項的設定。
pps
控管發布商提供的信號 (PPS) 設定。
privacyTreatments
控管發布商隱私權處理方式的設定。


adExpansion


pps


privacyTreatments


googletag.configPrivacyTreatmentsConfig

控管發布商隱私權處理方式的設定。

資源摘要
treatments
發布商要啟用的一系列隱私權處理方式。


treatments

  • treatments: "disablePersonalization"[]
  • 要啟用的一系列發布商隱私權處理方式。

  • 範例

    JavaScript

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

    JavaScript (舊版)

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

    TypeScript

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


googletag.configPublisherProvidedSignalsConfig

發布商提供的信號 (PPS) 設定物件。

資源摘要
taxonomies
包含分類對應的物件。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

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


taxonomies


googletag.configSlotSettingsConfig

版位層級設定的主要設定介面。

允許針對單一版位設定多個功能,一次 API 呼叫。

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

範例:

  • 系統只會修改 Slot.setConfig 呼叫中指定的功能。
      const slot = googletag.defineSlot("/1234567/example", [160, 600]);
    
      // Configure feature alpha.
      slot.setConfig({
          alpha: {...}
      });
    
      // Configure feature bravo. Feature alpha is unchanged.
      slot.setConfig({
         bravo: {...}
      });
    
  • 每次呼叫 Slot.setConfig 時,特定功能的所有設定都會更新。
      // Configure feature charlie to echo = 1, foxtrot = true.
      slot.setConfig({
          charlie: {
              echo: 1,
              foxtrot: true,
          }
      });
    
      // Update feature charlie to echo = 2. Since foxtrot was not specified,
      // the value is cleared.
      slot.setConfig({
          charlie: {
              echo: 2
          }
      });
    
  • 如要清除功能的所有設定,請傳遞 null
      // Configure features delta, golf, and hotel.
      slot.setConfig({
          delta: {...},
          golf: {...},
          hotel: {...},
      });
    
      // Feature delta and hotel are cleared, but feature golf remains set.
      slot.setConfig({
          delta: null,
          hotel: null,
      });
    

資源摘要
adExpansion
廣告展開控制項的設定。
componentAuction
要加入裝置端廣告競價的一系列元件競價。
interstitial
控制插頁式廣告版位行為的設定。


adExpansion


componentAuction


interstitial


googletag.configTaxonomyData

包含單一分類值的物件。

資源摘要
values
分類值的清單。


values

  • values: string[]
  • 分類值的清單。


googletag.eventsEvent

所有 GPT 事件的基本介面。下方所有 GPT 事件都會有下列欄位。

資源摘要
serviceName
觸發事件的服務名稱。
slot
觸發事件的版位。
另請參閱


serviceName

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


slot

  • slot: Slot
  • 觸發事件的版位。


googletag.eventsEventTypeMap

這是虛擬類型,可將事件名稱對應至其 Service.addEventListenerService.removeEventListener 的對應事件物件類型。文件僅供參考,僅供參考。

資源摘要
impressionViewable
rewardedSlotClosed
rewardedSlotGranted
rewardedSlotReady
slotOnload
events.SlotOnloadEvent 的別名。
slotRenderEnded
slotRequested
slotResponseReceived
slotVisibilityChanged


impressionViewable


rewardedSlotClosed


rewardedSlotGranted


rewardedSlotReady


slotOnload


slotRenderEnded


slotRequested


slotResponseReceived


slotVisibilityChanged


googletag.eventsImpressionViewableEvent

擴充 Event

曝光變為可視時,系統會根據 Active View 條件觸發此事件。

資源摘要
serviceName
觸發事件的服務名稱。
slot
觸發事件的版位。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

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


googletag.eventsRewardedSlotClosedEvent

擴充 Event

使用者關閉獎勵廣告版位時,會觸發此事件。獎勵可能會在發放前或發放後觸發。如要判斷是否已經獲得獎勵,請改用 events.RewardedSlotGrantedEvent

資源摘要
serviceName
觸發事件的服務名稱。
slot
觸發事件的版位。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

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


googletag.eventsRewardedSlotGrantedEvent

擴充 Event

獎勵觀看獎勵廣告後,就會觸發此事件。如果在符合獎勵條件前關閉廣告,系統就不會觸發這個事件。

資源摘要
payload
包含已授予獎勵相關資訊的物件。
serviceName
觸發事件的服務名稱。
slot
觸發事件的版位。
範例

JavaScript

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

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

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

JavaScript (舊版)

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

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

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

TypeScript

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

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

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


payload

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


googletag.eventsRewardedSlotReadyEvent

擴充 Event

獎勵廣告準備好顯示時,就會觸發此事件。發布商必須負責在廣告顯示前,讓使用者選擇是否觀看廣告。

資源摘要
serviceName
觸發事件的服務名稱。
slot
觸發事件的版位。
方法摘要
makeRewardedVisible
顯示獎勵廣告。
範例

JavaScript

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

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

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

JavaScript (舊版)

// This listener is called when a rewarded ad slot becomes ready to be
// displayed.
var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]);
googletag.pubads().addEventListener("rewardedSlotReady", function (event) {
  var slot = event.slot;
  console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed.");

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

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

TypeScript

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

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

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


makeRewardedVisible

  • makeRewardedVisible(): void
  • 顯示獎勵廣告。在使用者同意觀看廣告時,您不應呼叫這個方法。


googletag.eventsSlotOnloadEvent

擴充 Event

當廣告素材的 iframe 觸發載入事件時,會觸發這個事件。以同步顯示模式顯示互動式多媒體廣告時,不會使用 iframe,因此不會觸發 SlotOnloadEvent

資源摘要
serviceName
觸發事件的服務名稱。
slot
觸發事件的版位。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

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


googletag.eventsSlotRenderEndedEvent

擴充 Event

當廣告素材程式碼插入版位時,會觸發此事件。這個事件會在系統擷取廣告素材資源之前發生,因此廣告素材可能還不會顯示。如果您需要知道版位的所有廣告素材資源何時完成載入,請考慮改用 events.SlotOnloadEvent

資源摘要
advertiserId
已顯示廣告的廣告主 ID。
campaignId
已顯示廣告的廣告活動 ID。
companyIds
對已顯示的廣告出價的公司 ID。
creativeId
已顯示預訂廣告的廣告素材 ID。
creativeTemplateId
所顯示預訂廣告的廣告素材範本 ID。
isBackfill
廣告是否為候補廣告。
isEmpty
指出版位是否已傳回廣告。
labelIds
所顯示廣告的標籤 ID。
lineItemId
已顯示預訂廣告的委刊項 ID。
serviceName
觸發事件的服務名稱。
size
指出已顯示廣告素材的像素大小。
slot
觸發事件的版位。
slotContentChanged
指出版位內容是否已隨著實際顯示的廣告變更。
sourceAgnosticCreativeId
所顯示預訂或候補廣告的廣告素材 ID。
sourceAgnosticLineItemId
已顯示預訂或候補廣告的委刊項 ID。
yieldGroupIds
所顯示候補廣告的收益群組 ID。
範例

JavaScript

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

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

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

JavaScript (舊版)

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

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

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

TypeScript

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

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

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


advertiserId

  • advertiserId: null | number
  • 已顯示廣告的廣告主 ID。如果版位、候補廣告和廣告素材是由 PubAdsService 以外的服務顯示,則值為 null


campaignId

  • campaignId: null | number
  • 已顯示廣告的廣告活動 ID。如果版位、候補廣告和廣告素材是由 PubAdsService 以外的服務顯示,則值為 null


companyIds

  • companyIds: null | number[]
  • 對已顯示的廣告出價的公司 ID。如果是 PubAdsService 以外服務顯示的空白版位、預訂廣告和廣告素材,則值為 null


creativeId

  • creativeId: null | number
  • 已顯示預訂廣告的廣告素材 ID。如果版位、候補廣告和廣告素材是由 PubAdsService 以外的服務顯示,則值為 null


creativeTemplateId

  • creativeTemplateId: null | number
  • 所顯示預訂廣告的廣告素材範本 ID。如果版位、候補廣告和廣告素材是由 PubAdsService 以外的服務顯示,則值為 null


isBackfill

  • isBackfill: boolean
  • 廣告是否為候補廣告。如果廣告是候補廣告,則值為 true,否則值為 false


isEmpty

  • isEmpty: boolean
  • 指出版位是否已傳回廣告。如果未傳回廣告,值為 true,否則值為 false


labelIds

  • labelIds: null | number[]
  • 已顯示廣告的標籤 ID。如果版位、候補廣告和廣告素材是由 PubAdsService 以外的服務顯示,則值為 null


lineItemId

  • lineItemId: null | number
  • 已顯示預訂廣告的委刊項 ID。如果版位、候補廣告和廣告素材是由 PubAdsService 以外的服務顯示,則值為 null


size

  • size: null | string | number[]
  • 指出已顯示廣告素材的像素大小。範例:[728, 90]。若廣告版位是空的,則值為 null


slotContentChanged

  • slotContentChanged: boolean
  • 指出版位內容是否已隨著實際顯示的廣告變更。如果內容有所變更,值為 true,否則值為 false


sourceAgnosticCreativeId

  • sourceAgnosticCreativeId: null | number
  • 所顯示預訂或候補廣告的廣告素材 ID。如果廣告不是預訂或委刊項候補廣告,或廣告素材是由 PubAdsService 以外的服務顯示,則值為 null


sourceAgnosticLineItemId

  • sourceAgnosticLineItemId: null | number
  • 已顯示預訂或候補廣告的委刊項 ID。如果廣告不是預訂或委刊項候補廣告,或廣告素材是由 PubAdsService 以外的服務顯示,則值為 null


yieldGroupIds

  • yieldGroupIds: null | number[]
  • 所顯示候補廣告的收益群組 ID。如果是 PubAdsService 以外服務顯示的空白版位、預訂廣告和廣告素材,則值為 null


googletag.eventsSlotRequestedEvent

擴充 Event

已針對特定版位請求廣告時,會觸發此事件。

資源摘要
serviceName
觸發事件的服務名稱。
slot
觸發事件的版位。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

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


googletag.eventsSlotResponseReceived

擴充 Event

系統收到特定版位的廣告回應時,會觸發此事件。

資源摘要
serviceName
觸發事件的服務名稱。
slot
觸發事件的版位。
範例

JavaScript

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

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

JavaScript (舊版)

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

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

TypeScript

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

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


googletag.eventsSlotVisibilityChangedEvent

擴充 Event

每當廣告版位區域的畫面上百分比變更時,就會觸發此事件。事件會受到限制,且每 200 毫秒不會超過一次觸發事件。

資源摘要
inViewPercentage
廣告可見區域的百分比。
serviceName
觸發事件的服務名稱。
slot
觸發事件的版位。
範例

JavaScript

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

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

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

JavaScript (舊版)

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

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

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

TypeScript

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

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

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


inViewPercentage

  • inViewPercentage: number
  • 廣告可見區域的百分比。這個值是介於 0 到 100 之間的數字。


googletag.secureSignalsBidderSignalProvider

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

出價方安全信號供應商由 2 個部分組成:

  1. 收集器函式,會傳回可解析為安全信號的 Promise
  2. id,用於識別與信號相關聯的出價方。
如要傳回發布商的安全信號,請改用 secureSignals.PublisherSignalProvider

資源摘要
collectorFunction
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>


id

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


googletag.secureSignalsPublisherSignalProvider

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

發布商信號供應商由 2 個部分組成:

  1. 收集器函式,會傳回可解析為安全信號的 Promise
  2. networkCode,用來識別與信號相關聯的發布商。
如要為出價方傳回安全信號,請改用 secureSignals.BidderSignalProvider

資源摘要
collectorFunction
networkCode
與此安全信號相關聯的發布商聯播網代碼 (如廣告單元路徑所示)。
範例

JavaScript

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

JavaScript (舊版)

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

TypeScript

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


collectorFunction

  • collectorFunction: () => Promise<string>


networkCode

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


googletag.secureSignalsSecureSignalProvidersArray

用於管理安全信號的介面。

方法摘要
clearAllCache
從快取中清除所有收集器的信號,因此可降低系統在這次和之後網頁瀏覽的廣告請求中納入信號的可能性。
push
在信號提供者陣列中加入新的 secureSignals.SecureSignalProvider,然後開始信號產生程序。


clearAllCache

  • clearAllCache(): void
  • 從快取中清除所有收集器的信號,因此可降低系統在這次和日後網頁瀏覽的廣告請求中納入信號的可能性。僅應用於有意義的狀態變更,例如代表新使用者的事件 (例如登入、登出、註冊)。


push