This reference uses TypeScript notation to describe types. The following table provides a brief explanation by example.
Type expression | |
---|---|
string |
The primitive string type. |
string[] |
An array type, where values may only be strings. |
number | string |
A union type, where the value may be either a number or a string. |
Array<number | string> |
An array type, where values are a complex (union) type. |
[number, string] |
A tuple type, where the value is a two-element array that must contain a number and a string in that order. |
Slot |
An object type, where the value is an instance of googletag.Slot . |
() => void |
A function type with no defined arguments and no return value. |
To learn more about supported types and type expressions, refer to the TypeScript Handbook .
Type annotations
A colon after a variable, parameter name, property name, or function signature denotes a type annotation. Type annotations describe the types the element to the left of the colon can accept or return. The following table shows examples of type annotations you may see in this reference.
Type annotation | |
---|---|
param: string |
Indicates that param accepts or returns a string value. This syntax is used
for variables, parameters, properties, and return types.
|
param?: number | string |
Indicates that param is optional, but accepts either a number or a string
when specified. This syntax is used for parameters and properties.
|
...params: Array<() => void> |
Indicates that params is a
rest parameter
that accepts functions. Rest parameters accept an unbounded number of values of the
specified type.
|
googletag
Namespaces | |
---|---|
config | Main configuration interface for page-level settings. |
enums | This is the namespace that GPT uses for enum types. |
events | This is the namespace that GPT uses for Events. |
secure | This is the namespace that GPT uses for managing secure signals. |
Interfaces | |
---|---|
Command | The command array accepts a sequence of functions and invokes them in order. |
Companion | Companion Ads service. |
Privacy | Configuration object for privacy settings. |
Pub | Publisher Ads service. |
Response | An object representing a single ad response. |
Rewarded | An object representing the reward associated with a rewarded ad. |
Safe | Configuration object for SafeFrame containers. |
Service | Base service class that contains methods common for all services. |
Size | Builder for size mapping specification objects. |
Slot | Slot is an object representing a single ad slot on a page. |
Type Aliases | |
---|---|
General | A valid size configuration for a slot, which can be one or multiple sizes. |
Multi | A list of single valid sizes. |
Named | Named sizes that a slot can have. |
Single | A single valid size for a slot. |
Single | Array of two numbers representing [width, height]. |
Size | A mapping of viewport size to ad sizes. |
Size | A list of size mappings. |
Variables | |
---|---|
api | Flag indicating that the GPT API is loaded and ready to be called. |
cmd | Reference to the global command queue for asynchronous execution of GPT-related calls. |
pubads | Flag indicating that PubAdsService is enabled, loaded and fully operational. |
secure | Reference to the secure signal providers array. |
Functions | |
---|---|
companion | Returns a reference to the CompanionAdsService. |
define | Constructs an out-of-page ad slot with the given ad unit path. |
define | Constructs an ad slot with a given ad unit path and size and associates it with the ID of a div element on the page that will contain the ad. |
destroy | Destroys the given slots, removing all related objects and references of those slots from GPT. |
disable | Disables the Google Publisher Console. |
display | Instructs slot services to render the slot. |
enable | Enables all GPT services that have been defined for ad slots on the page. |
get | Returns the current version of GPT. |
open | Opens the Google Publisher Console. |
pubads | Returns a reference to the PubAdsService. |
set | Sets the title for all ad container iframes created by PubAdsService, from this point onwards. |
set | Sets general configuration options for the page. |
size | Creates a new SizeMappingBuilder. |
Type Aliases
GeneralSize
GeneralSize: SingleSize | MultiSize
MultiSize
MultiSize: SingleSize[]
NamedSize
NamedSize: "fluid" | ["fluid"]
- fluid: the ad container takes 100% width of parent div and then resizes its height to fit creative content. Similar to how regular block elements on a page behave. Used for native ads (see related article). Note that both
fluid
and['fluid']
are acceptable forms to declare a slot size as fluid.
SingleSize
SingleSize: SingleSizeArray | NamedSize
SingleSizeArray
SingleSizeArray: [number, number]
SizeMapping
SizeMapping: [SingleSizeArray, GeneralSize]
SizeMappingArray
SizeMappingArray: SizeMapping[]
Variables
Const
apiReady
apiReady: boolean | undefined
undefined
until the API is ready.Note that the recommended way of handling async is to use googletag.cmd to queue callbacks for when GPT is ready. These callbacks do not have to check googletag.apiReady as they are guaranteed to execute once the API is set up.
Const
cmd
cmd: ((this: typeof globalThis) => void)[] | CommandArray
The
googletag.cmd
variable is initialized to an empty JavaScript array by the GPT tag syntax on the page, and cmd.push
is the standard Array.push
method that adds an element to the end of the array. When the GPT JavaScript is loaded, it looks through the array and executes all the functions in order. The script then replaces cmd
with a CommandArray object whose push method is defined to execute the function argument passed to it. This mechanism allows GPT to reduce perceived latency by fetching the JavaScript asynchronously while allowing the browser to continue rendering the page.- Example
JavaScript
googletag.cmd.push(() => { googletag.defineSlot("/1234567/sports", [160, 600]).addService(googletag.pubads()); });
JavaScript (legacy)
googletag.cmd.push(function () { googletag.defineSlot("/1234567/sports", [160, 600]).addService(googletag.pubads()); });
TypeScript
googletag.cmd.push(() => { googletag.defineSlot("/1234567/sports", [160, 600])!.addService(googletag.pubads()); });
Const
pubadsReady
pubadsReady: boolean | undefined
undefined
until enableServices is called and PubAdsService is loaded and initialized.secureSignalProviders
secureSignalProviders: SecureSignalProvider[] | SecureSignalProvidersArray | undefined
The secure signal providers array accepts a sequence of signal-generating functions and invokes them in order. It is intended to replace a standard array that is used to enqueue signal-generating functions to be invoked once GPT is loaded.
- Example
JavaScript
window.googletag = window.googletag || { cmd: [] }; googletag.secureSignalProviders = googletag.secureSignalProviders || []; googletag.secureSignalProviders.push({ id: "collector123", collectorFunction: () => { return Promise.resolve("signal"); }, });
JavaScript (legacy)
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"); }, });
Functions
companionAds
companionAds(): CompanionAdsService
Returns | |
---|---|
CompanionAdsService | The Companion Ads service. |
defineOutOfPageSlot
defineOutOfPageSlot(adUnitPath: string, div?: string | OutOfPageFormat): Slot | null
For custom out-of-page ads,
div
is the ID of the div element that will contain the ad. See the article on out-of-page creatives for more details.For GPT managed out-of-page ads,
div
is a supported OutOfPageFormat.- Example
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 (legacy)
// 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);
- See also
Parameters | |
---|---|
adUnitPath: string | Full ad unit path with the network code and ad unit code. |
| ID of the div that will contain this ad unit or OutOfPageFormat. |
Returns | |
---|---|
Slot | null | The newly created slot, or null if a slot cannot be created. |
defineSlot
defineSlot(adUnitPath: string, size: GeneralSize, div?: string): Slot | null
- Example
JavaScript
googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
JavaScript (legacy)
googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
TypeScript
googletag.defineSlot("/1234567/sports", [728, 90], "div-1");
Parameters | |
---|---|
adUnitPath: string | Full ad unit path with the network code and unit code. |
size: GeneralSize | Width and height of the added slot. This is the size that is used in the ad request if no responsive size mapping is provided or the size of the viewport is smaller than the smallest size provided in the mapping. |
| ID of the div that will contain this ad unit. |
Returns | |
---|---|
Slot | null | The newly created slot, or null if a slot cannot be created. |
destroySlots
destroySlots(slots?: Slot[]): boolean
Calling this API on a slot clears the ad and removes the slot object from the internal state maintained by GPT. Calling any more functions on the slot object will result in undefined behavior. Note the browser may still not free the memory associated with that slot if a reference to it is maintained by the publisher page. Calling this API makes the div associated with that slot available for reuse.
In particular, destroying a slot removes the ad from GPT's long-lived pageview, so future requests will not be influenced by roadblocks or competitive exclusions involving this ad. Failure to call this function before removing a slot's div from the page will result in undefined behavior.
- Example
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 (legacy)
// 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();
Parameters | |
---|---|
| The array of slots to destroy. Array is optional; all slots will be destroyed if it is unspecified. |
Returns | |
---|---|
boolean | true if slots have been destroyed, false otherwise. |
disablePublisherConsole
disablePublisherConsole(): void
- See also
display
display(divOrSlot: string | Element | Slot): void
If single request architecture (SRA) is being used, all unfetched ad slots at the time this method is called will be fetched at once. To force an ad slot not to display, the entire div must be removed.
Parameters | |
---|---|
divOrSlot: string | Element | Slot | Either the ID of the div element containing the ad slot or the div element, or the slot object. If a div element is provided, it must have an 'id' attribute which matches the ID passed into defineSlot. |
enableServices
enableServices(): void
getVersion
getVersion(): string
- See also
Returns | |
---|---|
string | The currently executing GPT version string. |
openConsole
openConsole(div?: string): void
- Example
JavaScript
// Calling with div ID. googletag.openConsole("div-1"); // Calling without div ID. googletag.openConsole();
JavaScript (legacy)
// 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();
- See also
Parameters | |
---|---|
| An ad slot div ID. This value is optional. When provided, the Publisher Console will attempt to open with details of the specified ad slot in view. |
pubads
pubads(): PubAdsService
Returns | |
---|---|
PubAdsService | The Publisher Ads service. |
setAdIframeTitle
setAdIframeTitle(title: string): void
- Example
JavaScript
googletag.setAdIframeTitle("title");
JavaScript (legacy)
googletag.setAdIframeTitle("title");
TypeScript
googletag.setAdIframeTitle("title");
Parameters | |
---|---|
title: string | The new title for all ad container iframes. |
setConfig
setConfig(config: PageSettingsConfig): void
Parameters | |
---|---|
config: PageSettingsConfig |
sizeMapping
sizeMapping(): SizeMappingBuilder
googletag.CommandArray
Methods | |
---|---|
push | Executes the sequence of functions specified in the arguments in order. |
Methods
push
push(...f: ((this: typeof globalThis) => void)[]): number
- Example
JavaScript
googletag.cmd.push(() => { googletag.defineSlot("/1234567/sports", [160, 600]).addService(googletag.pubads()); });
JavaScript (legacy)
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()); });
Parameters | |
---|---|
| A JavaScript function to be executed. The runtime binding will always be globalThis . Consider passing an arrow function to retain the this value of the enclosing lexical context. |
Returns | |
---|---|
number | The number of commands processed so far. This is compatible with Array.push 's return value (the current length of the array). |
googletag.CompanionAdsService
ExtendsMethods | |
---|---|
add | Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page. Inherited from |
get | Get the list of slots associated with this service. Inherited from |
remove | Removes a previously registered listener. Inherited from |
set | Sets whether companion slots that have not been filled will be automatically backfilled. |
Methods
setRefreshUnfilledSlots
setRefreshUnfilledSlots(value: boolean): void
This method can be called multiple times during the page's lifetime to turn backfill on and off. Only slots that are also registered with the PubAdsService will be backfilled. Due to policy restrictions, this method is not designed to fill empty companion slots when an Ad Exchange video is served.
- Example
JavaScript
googletag.companionAds().setRefreshUnfilledSlots(true);
JavaScript (legacy)
googletag.companionAds().setRefreshUnfilledSlots(true);
TypeScript
googletag.companionAds().setRefreshUnfilledSlots(true);
Parameters | |
---|---|
value: boolean | true to automatically backfill unfilled slots, false to leave them unchanged. |
googletag.PrivacySettingsConfig
Properties | |
---|---|
child | Indicates whether the page should be treated as child-directed. |
limited | Enables serving to run in limited ads mode to aid in publisher regulatory compliance needs. |
non | Enables serving to run in non-personalized ads mode to aid in publisher regulatory compliance needs. |
restrict | Enables serving to run in restricted processing mode to aid in publisher regulatory compliance needs. |
traffic | Indicates whether requests represent purchased or organic traffic. |
under | Indicates whether to mark ad requests as coming from users under the age of consent. |
- See also
Properties
Optional
childDirectedTreatment
childDirectedTreatment?: null | boolean
null
to clear the configuration.Optional
limitedAds
limitedAds?: boolean
You can instruct GPT to request limited ads in two ways:
- Automatically, by using a signal from an IAB TCF v2.0 consent management platform.
- Manually, by setting the value of this field to
true
.
Note that it is not necessary to manually enable limited ads when a CMP is in use.
- Example
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 (legacy)
// 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, });
- See also
Optional
nonPersonalizedAds
nonPersonalizedAds?: boolean
Optional
restrictDataProcessing
restrictDataProcessing?: boolean
Optional
trafficSource
trafficSource?: TrafficSource
undefined
in reporting.- Example
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 (legacy)
// Indicate requests represent organic traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.ORGANIC, }); // Indicate requests represent purchased traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.PURCHASED, });
TypeScript
// Indicate requests represent organic traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.ORGANIC, }); // Indicate requests represent purchased traffic. googletag.pubads().setPrivacySettings({ trafficSource: googletag.enums.TrafficSource.PURCHASED, });
Optional
underAgeOfConsent
underAgeOfConsent?: null | boolean
null
to clear the configuration.googletag.PubAdsService
ExtendsMethods | |
---|---|
add | Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page. Inherited from |
clear | Removes the ads from the given slots and replaces them with blank content. |
clear | Clears all page-level ad category exclusion labels. |
clear | Clears custom targeting parameters for a specific key or for all keys. |
collapse | Enables collapsing of slot divs so that they don't take up any space on the page when there is no ad content to display. |
disable | Disables requests for ads on page load, but allows ads to be requested with a PubAdsService.refresh call. |
display | Constructs and displays an ad slot with the given ad unit path and size. |
enable | Enables lazy loading in GPT as defined by the config object. |
enable | Enables single request mode for fetching multiple ads at the same time. |
enable | Signals to GPT that video ads will be present on the page. |
get | Returns the value for the AdSense attribute associated with the given key. |
get | Returns the attribute keys that have been set on this service. |
get | Get the list of slots associated with this service. Inherited from |
get | Returns a specific custom service-level targeting parameter that has been set. |
get | Returns the list of all custom service-level targeting keys that have been set. |
is | Returns whether or not initial requests for ads was successfully disabled by a previous PubAdsService.disableInitialLoad call. |
refresh | Fetches and displays new ads for specific or all slots on the page. |
remove | Removes a previously registered listener. Inherited from |
set | Sets values for AdSense attributes that apply to all ad slots under the Publisher Ads service. |
set | Sets a page-level ad category exclusion for the given label name. |
set | Enables and disables horizontal centering of ads. |
set | Configures whether all ads on the page should be forced to be rendered using a SafeFrame container. |
set | Passes location information from websites so you can geo-target line items to specific locations. |
set | Allows configuration of all privacy settings from a single API using a config object. |
set | Sets the value for the publisher-provided ID. |
set | Sets the page-level preferences for SafeFrame configuration. |
set | Sets custom targeting parameters for a given key that apply to all Publisher Ads service ad slots. |
set | Sets the video content information to be sent along with the ad requests for targeting and content exclusion purposes. |
update | Changes the correlator that is sent with ad requests, effectively starting a new page view. |
Methods
clear
clear(slots?: Slot[]): boolean
In particular, clearing a slot removes the ad from GPT's long-lived pageview, so future requests will not be influenced by roadblocks or competitive exclusions involving this ad.
- Example
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 (legacy)
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();
Parameters | |
---|---|
| The array of slots to clear. Array is optional; all slots will be cleared if it is unspecified. |
Returns | |
---|---|
boolean | Returns true if slots have been cleared, false otherwise. |
clearCategoryExclusions
clearCategoryExclusions(): PubAdsService
- Example
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 (legacy)
// 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.
- See also
Returns | |
---|---|
PubAdsService | The service object on which the method was called. |
clearTargeting
clearTargeting(key?: string): PubAdsService
- Example
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 (legacy)
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.
- See also
Parameters | |
---|---|
| Targeting parameter key. The key is optional; all targeting parameters will be cleared if it is unspecified. |
Returns | |
---|---|
PubAdsService | The service object on which the method was called. |
collapseEmptyDivs
collapseEmptyDivs(collapseBeforeAdFetch?: boolean): boolean
Parameters | |
---|---|
| Whether to collapse the slots even before the ads are fetched. This parameter is optional; if not provided, false will be used as the default value. |
Returns | |
---|---|
boolean | Returns true if div collapse mode was enabled and false if it is impossible to enable collapse mode because the method was called after the service was enabled. |
disableInitialLoad
disableInitialLoad(): void
refresh
.display
display(adUnitPath: string, size: GeneralSize, div?: string | Element, clickUrl?: string): void
Note: When this method is called, a snapshot of the slot and page state is created to ensure consistency when sending the ad request and rendering the response. Any changes that are made to the slot or page state after this method is called (including targeting, privacy settings, force SafeFrame, etc.) will only apply to subsequent
display()
or refresh()
requests.- Example
JavaScript
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
JavaScript (legacy)
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
TypeScript
googletag.pubads().display("/1234567/sports", [728, 90], "div-1");
Parameters | |
---|---|
adUnitPath: string | The ad unit path of slot to be rendered. |
size: GeneralSize | Width and height of the slot. |
| Either the ID of the div containing the slot or the div element itself. |
| The click URL to use on this slot. |
enableLazyLoad
enableLazyLoad(config?: {
fetchMarginPercent?: number;
mobileScaling?: number;
renderMarginPercent?: number;
}): void
Note: Lazy fetching in SRA only works if all slots are outside the fetching margin.
- Example
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 (legacy)
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, });
Parameters | |
---|---|
| Configuration object allows customization of lazy behavior. Any omitted configurations will use a default set by Google that will be tuned over time. To disable a particular setting, such as a fetching margin, set the value to -1 .
|
enableSingleRequest
enableSingleRequest(): boolean
Returns | |
---|---|
boolean | Returns true if single request mode was enabled and false if it is impossible to enable single request mode because the method was called after the service was enabled. |
enableVideoAds
enableVideoAds(): void
get
get(key: string): null | string
- Example
JavaScript
googletag.pubads().set("adsense_background_color", "#FFFFFF"); googletag.pubads().get("adsense_background_color"); // Returns '#FFFFFF'.
JavaScript (legacy)
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'.
- See also
Parameters | |
---|---|
key: string | Name of the attribute to look for. |
Returns | |
---|---|
null | string | Current value for the attribute key, or null if the key is not present. |
getAttributeKeys
getAttributeKeys(): string[]
- Example
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 (legacy)
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'].
Returns | |
---|---|
string[] | Array of attribute keys set on this service. Ordering is undefined. |
getTargeting
getTargeting(key: string): string[]
- Example
JavaScript
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().getTargeting("interests"); // Returns ['sports']. googletag.pubads().getTargeting("age"); // Returns [] (empty array).
JavaScript (legacy)
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).
Parameters | |
---|---|
key: string | The targeting key to look for. |
Returns | |
---|---|
string[] | The values associated with this key, or an empty array if there is no such key. |
getTargetingKeys
getTargetingKeys(): string[]
- Example
JavaScript
googletag.pubads().setTargeting("interests", "sports"); googletag.pubads().setTargeting("colors", "blue"); googletag.pubads().getTargetingKeys(); // Returns ['interests', 'colors'].
JavaScript (legacy)
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'].
Returns | |
---|---|
string[] | Array of targeting keys. Ordering is undefined. |
isInitialLoadDisabled
isInitialLoadDisabled(): boolean
Returns | |
---|---|
boolean | Returns true if a previous call to PubAdsService.disableInitialLoad was successful, false otherwise. |
refresh
refresh(slots?: null | Slot[], options?: {
changeCorrelator: boolean;
}): void
For proper behavior across all browsers, calling
refresh
must be preceded by a call to display
the ad slot. If the call to display
is omitted, refresh may behave unexpectedly. If desired, the PubAdsService.disableInitialLoad method can be used to stop display
from fetching an ad.Refreshing a slot removes the old ad from GPT's long-lived pageview, so future requests will not be influenced by roadblocks or competitive exclusions involving that ad.
- Example
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 (legacy)
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 });
Parameters | |
---|---|
| The slots to refresh. Array is optional; all slots will be refreshed if it is unspecified. |
| Configuration options associated with this refresh call.
|
set
set(key: string, value: string): PubAdsService
Calling this more than once for the same key will override previously set values for that key. All values must be set before calling
display
or refresh
.- Example
JavaScript
googletag.pubads().set("adsense_background_color", "#FFFFFF");
JavaScript (legacy)
googletag.pubads().set("adsense_background_color", "#FFFFFF");
TypeScript
googletag.pubads().set("adsense_background_color", "#FFFFFF");
- See also
Parameters | |
---|---|
key: string | The name of the attribute. |
value: string | Attribute value. |
Returns | |
---|---|
PubAdsService | The service object on which the method was called. |
setCategoryExclusion
setCategoryExclusion(categoryExclusion: string): PubAdsService
- Example
JavaScript
// Label = AirlineAd. googletag.pubads().setCategoryExclusion("AirlineAd");
JavaScript (legacy)
// Label = AirlineAd. googletag.pubads().setCategoryExclusion("AirlineAd");
TypeScript
// Label = AirlineAd. googletag.pubads().setCategoryExclusion("AirlineAd");
- See also
Parameters | |
---|---|
categoryExclusion: string | The ad category exclusion label to add. |
Returns | |
---|---|
PubAdsService | The service object on which the method was called. |
setCentering
setCentering(centerAds: boolean): void
This method should be invoked before calling
display
or refresh
because only ads that are requested after calling this method will be centered.- Example
JavaScript
// Make ads centered. googletag.pubads().setCentering(true);
JavaScript (legacy)
// Make ads centered. googletag.pubads().setCentering(true);
TypeScript
// Make ads centered. googletag.pubads().setCentering(true);
Parameters | |
---|---|
centerAds: boolean | true to center ads, false to left-align them. |
setForceSafeFrame
setForceSafeFrame(forceSafeFrame: boolean): PubAdsService
Please keep the following things in mind while using this API:
- This setting will only take effect for subsequent ad requests made for the respective slots.
- The slot level setting, if specified, will always override the page level setting.
- If set to
true
(at slot-level or page level), the ad will always be rendered using a SafeFrame container independent of the choice made in the Google Ad Manager UI. - However, if set to
false
or left unspecified, the ad will be rendered using a SafeFrame container depending on the type of creative and the selection made in the Google Ad Manager UI. - This API should be used with caution as it could impact the behaviour of creatives that attempt to break out of their iFrames or rely on them being rendered directly in a publishers page.
- Example
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 (legacy)
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");
- See also
Parameters | |
---|---|
forceSafeFrame: boolean | true to force all ads on the page to be rendered in SafeFrames and false to change the previous setting to false. Setting this to false when unspecified earlier, won't change anything. |
Returns | |
---|---|
PubAdsService | The service object on which the function was called. |
setLocation
setLocation(address: string): PubAdsService
- Example
JavaScript
// Postal code: googletag.pubads().setLocation("10001,US");
JavaScript (legacy)
// Postal code: googletag.pubads().setLocation("10001,US");
TypeScript
// Postal code: googletag.pubads().setLocation("10001,US");
Parameters | |
---|---|
address: string | Freeform address. |
Returns | |
---|---|
PubAdsService | The service object on which the method was called. |
setPrivacySettings
setPrivacySettings(privacySettings: PrivacySettingsConfig): PubAdsService
- Example
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 (legacy)
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, });
Parameters | |
---|---|
privacySettings: PrivacySettingsConfig | Object containing privacy settings config. |
Returns | |
---|---|
PubAdsService | The service object on which the function was called. |
setPublisherProvidedId
setPublisherProvidedId(ppid: string): PubAdsService
- Example
JavaScript
googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
JavaScript (legacy)
googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
TypeScript
googletag.pubads().setPublisherProvidedId("12JD92JD8078S8J29SDOAKC0EF230337");
Parameters | |
---|---|
ppid: string | An alphanumeric ID provided by the publisher. Must be between 32 and 150 characters. |
Returns | |
---|---|
PubAdsService | The service object on which the method was called. |
setSafeFrameConfig
setSafeFrameConfig(config: SafeFrameConfig): PubAdsService
These page-level preferences will be overridden by slot-level preferences, if specified.
- Example
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 (legacy)
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");
- See also
Parameters | |
---|---|
config: SafeFrameConfig | The configuration object. |
Returns | |
---|---|
PubAdsService | The service object on which the method was called. |
setTargeting
setTargeting(key: string, value: string | string[]): PubAdsService
- Example
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 (legacy)
// 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"]);
- See also
Parameters | |
---|---|
key: string | Targeting parameter key. |
value: string | string[] | Targeting parameter value or array of values. |
Returns | |
---|---|
PubAdsService | The service object on which the method was called. |
setVideoContent
setVideoContent(videoContentId: string, videoCmsId: string): void
videoContentId
and videoCmsId
, use the values that are provided to the Google Ad Manager content ingestion service.- See also
Parameters | |
---|---|
videoContentId: string | The video content ID. |
videoCmsId: string | The video CMS ID. |
updateCorrelator
updateCorrelator(): PubAdsService
Note: this has no effect on GPT's long-lived pageview, which automatically reflects the ads actually on the page and has no expiration time.
- Example
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 (legacy)
// 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.
Returns | |
---|---|
PubAdsService | The service object on which the function was called. |
googletag.ResponseInformation
Properties | |
---|---|
advertiser | The ID of the advertiser. |
campaign | The ID of the campaign. |
creative | The ID of the creative. |
creative | The template ID of the ad. |
line | The ID of the line item. |
- See also
Properties
advertiserId
advertiserId: null | number
campaignId
campaignId: null | number
creativeId
creativeId: null | number
creativeTemplateId
creativeTemplateId: null | number
lineItemId
lineItemId: null | number
googletag.RewardedPayload
Properties | |
---|---|
amount | The number of items included in the reward. |
type | The type of item included in the reward (for example, "coin"). |
- See also
Properties
amount
amount: number
type
type: string
googletag.SafeFrameConfig
Properties | |
---|---|
allow | Whether SafeFrame should allow ad content to expand by overlaying page content. |
allow | Whether SafeFrame should allow ad content to expand by pushing page content. |
sandbox | Whether SafeFrame should use the HTML5 sandbox attribute to prevent top level navigation without user interaction. |
use | Deprecated. Whether SafeFrame should use randomized subdomains for Reservation creatives. |
- See also
Properties
Optional
allowOverlayExpansion
allowOverlayExpansion?: boolean
Optional
allowPushExpansion
allowPushExpansion?: boolean
Optional
sandbox
sandbox?: boolean
true
(cannot be forced to false
). Note that the sandbox attribute disables plugins (e.g. Flash).Optional
useUniqueDomain
useUniqueDomain?: null | boolean
null
to clear the stored value.Note: this feature is enabled by default.
- See also
googletag.Service
Methods | |
---|---|
add | Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page. |
get | Get the list of slots associated with this service. |
remove | Removes a previously registered listener. |
Methods
addEventListener
addEventListener<K extends keyof EventTypeMap>(eventType: K, listener: ((arg: EventTypeMap[K]) => void)): Service
- events.GameManualInterstitialSlotClosedEvent
- events.GameManualInterstitialSlotReadyEvent
- events.ImpressionViewableEvent
- events.RewardedSlotClosedEvent
- events.RewardedSlotGrantedEvent
- events.RewardedSlotReadyEvent
- events.SlotOnloadEvent
- events.SlotRenderEndedEvent
- events.SlotRequestedEvent
- events.SlotResponseReceived
- events.SlotVisibilityChangedEvent
- Example
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 (legacy)
// 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. } });
- See also
Parameters | |
---|---|
eventType: K | A string representing the type of event generated by GPT. Event types are case sensitive. |
listener: ((arg: EventTypeMap[K]) => void) | Function that takes a single event object argument. |
Returns | |
---|---|
Service | The service object on which the method was called. |
getSlots
removeEventListener
removeEventListener<K extends keyof EventTypeMap>(eventType: K, listener: ((event: EventTypeMap[K]) => void)): void
- Example
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 (legacy)
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(); });
Parameters | |
---|---|
eventType: K | A string representing the type of event generated by GPT. Event types are case sensitive. |
listener: ((event: EventTypeMap[K]) => void) | Function that takes a single event object argument. |
googletag.SizeMappingBuilder
Methods | |
---|---|
add | Adds a mapping from a single-size array (representing the viewport) to a single- or multi-size array representing the slot. |
build | Builds a size map specification from the mappings added to this builder. |
- See also
Methods
addSize
addSize(viewportSize: SingleSizeArray, slotSize: GeneralSize): SizeMappingBuilder
- Example
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 (legacy)
// 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]
Parameters | |
---|---|
viewportSize: SingleSizeArray | The size of the viewport for this mapping entry. |
slotSize: GeneralSize | The sizes of the slot for this mapping entry. |
Returns | |
---|---|
SizeMappingBuilder | A reference to this builder. |
build
build(): null | SizeMappingArray
If any invalid mappings have been supplied, this method will return
null
. Otherwise it returns a specification in the correct format to pass to Slot.defineSizeMapping.Note: the behavior of the builder after calling this method is undefined.
Returns | |
---|---|
null | SizeMappingArray | The result built by this builder. Can be null if invalid size mappings were supplied. |
googletag.Slot
Methods | |
---|---|
add | Adds a Service to this slot. |
clear | Clears all slot-level ad category exclusion labels for this slot. |
clear | Clears specific or all custom slot-level targeting parameters for this slot. |
define | Sets an array of mappings from a minimum viewport size to slot size for this slot. |
get | Returns the value for the AdSense attribute associated with the given key for this slot. |
get | Returns the full path of the ad unit, with the network code and ad unit path. |
get | Returns the list of attribute keys set on this slot. |
get | Returns the ad category exclusion labels for this slot. |
get | Returns the ad response information. |
get | Returns the ID of the slot div provided when the slot was defined. |
get | Returns a specific custom targeting parameter set on this slot. |
get | Returns the list of all custom targeting keys set on this slot. |
set | Sets a value for an AdSense attribute on this ad slot. |
set | Sets a slot-level ad category exclusion label on this slot. |
set | Sets the click URL to which users will be redirected after clicking on the ad. |
set | Sets whether the slot div should be hidden when there is no ad in the slot. |
set | Sets general configuration options for this slot. |
set | Configures whether ads in this slot should be forced to be rendered using a SafeFrame container. |
set | Sets the slot-level preferences for SafeFrame configuration. |
set | Sets a custom targeting parameter for this slot. |
update | Sets custom targeting parameters for this slot, from a key:value map in a JSON object. |
Methods
addService
addService(service: Service): Slot
- Example
JavaScript
googletag.defineSlot("/1234567/sports", [160, 600], "div").addService(googletag.pubads());
JavaScript (legacy)
googletag.defineSlot("/1234567/sports", [160, 600], "div").addService(googletag.pubads());
TypeScript
googletag.defineSlot("/1234567/sports", [160, 600], "div")!.addService(googletag.pubads());
Parameters | |
---|---|
service: Service | The service to be added. |
Returns | |
---|---|
Slot | The slot object on which the method was called. |
clearCategoryExclusions
clearCategoryExclusions(): Slot
- Example
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 (legacy)
// 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.
Returns | |
---|---|
Slot | The slot object on which the method was called. |
clearTargeting
clearTargeting(key?: string): Slot
- Example
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 (legacy)
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.
- See also
Parameters | |
---|---|
| Targeting parameter key. The key is optional; all targeting parameters will be cleared if it is unspecified. |
Returns | |
---|---|
Slot | The slot object on which the method was called. |
defineSizeMapping
defineSizeMapping(sizeMapping: SizeMappingArray): Slot
- Example
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 (legacy)
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!);
- See also
Parameters | |
---|---|
sizeMapping: SizeMappingArray | Array of size mappings. You can use SizeMappingBuilder to create it. Each size mapping is an array of two elements: SingleSizeArray and GeneralSize. |
Returns | |
---|---|
Slot | The slot object on which the method was called. |
get
get(key: string): null | string
- Example
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 (legacy)
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'.
- See also
Parameters | |
---|---|
key: string | Name of the attribute to look for. |
Returns | |
---|---|
null | string | Current value for the attribute key, or null if the key is not present. |
getAdUnitPath
getAdUnitPath(): string
- Example
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); slot.getAdUnitPath(); // Returns '/1234567/sports'.
JavaScript (legacy)
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'.
Returns | |
---|---|
string | Ad unit path. |
getAttributeKeys
getAttributeKeys(): string[]
- Example
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 (legacy)
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'].
Returns | |
---|---|
string[] | Array of attribute keys. Ordering is undefined. |
getCategoryExclusions
getCategoryExclusions(): string[]
- Example
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .setCategoryExclusion("AirlineAd") .setCategoryExclusion("TrainAd") .addService(googletag.pubads()); slot.getCategoryExclusions(); // Returns ['AirlineAd', 'TrainAd'].
JavaScript (legacy)
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'].
Returns | |
---|---|
string[] | The ad category exclusion labels for this slot, or an empty array if none have been set. |
getResponseInformation
getResponseInformation(): null | ResponseInformation
null
will be returned.Returns | |
---|---|
null | ResponseInformation | The latest ad response information, or null if the slot has no ad. |
getSlotElementId
getSlotElementId(): string
div
provided when the slot was defined.- Example
JavaScript
const slot = googletag .defineSlot("/1234567/sports", [160, 600], "div") .addService(googletag.pubads()); slot.getSlotElementId(); // Returns 'div'.
JavaScript (legacy)
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'.
Returns | |
---|---|
string | Slot div ID. |
getTargeting
getTargeting(key: string): string[]
- Example
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 (legacy)
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).
Parameters | |
---|---|
key: string | The targeting key to look for. |
Returns | |
---|---|
string[] | The values associated with this key, or an empty array if there is no such key. |
getTargetingKeys
getTargetingKeys(): string[]
- Example
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 (legacy)
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'].
Returns | |
---|---|
string[] | Array of targeting keys. Ordering is undefined. |
set
set(key: string, value: string): Slot
Calling this method more than once for the same key will override previously set values for that key. All values must be set before calling
display
or refresh
.- Example
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 (legacy)
// 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());
- See also
Parameters | |
---|---|
key: string | The name of the attribute. |
value: string | Attribute value. |
Returns | |
---|---|
Slot | The slot object on which the method was called. |
setCategoryExclusion
setCategoryExclusion(categoryExclusion: string): Slot
- Example
JavaScript
// Label = AirlineAd googletag .defineSlot("/1234567/sports", [160, 600], "div") .setCategoryExclusion("AirlineAd") .addService(googletag.pubads());
JavaScript (legacy)
// 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());
- See also
Parameters | |
---|---|
categoryExclusion: string | The ad category exclusion label to add. |
Returns | |
---|---|
Slot | The slot object on which the method was called. |
setClickUrl
setClickUrl(value: string): Slot
The Google Ad Manager servers still record a click even if the click URL is replaced. Any landing page URL associated with the creative that is served is appended to the provided value. Subsequent calls overwrite the value. This works only for non-SRA requests.
- Example
JavaScript
googletag .defineSlot("/1234567/sports", [160, 600], "div") .setClickUrl("http://www.example.com?original_click_url=") .addService(googletag.pubads());
JavaScript (legacy)
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());
Parameters | |
---|---|
value: string | The click URL to set. |
Returns | |
---|---|
Slot | The slot object on which the method was called. |
setCollapseEmptyDiv
setCollapseEmptyDiv(collapse: boolean, collapseBeforeAdFetch?: boolean): Slot
div
should be hidden when there is no ad in the slot. This overrides the service-level settings.- Example
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 (legacy)
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.
Parameters | |
---|---|
collapse: boolean | Whether to collapse the slot if no ad is returned. |
| Whether to collapse the slot even before an ad is fetched. Ignored if collapse is not true . |
Returns | |
---|---|
Slot | The slot object on which the method was called. |
setConfig
setConfig(slotConfig: SlotSettingsConfig): void
Parameters | |
---|---|
slotConfig: SlotSettingsConfig | The configuration object. |
setForceSafeFrame
setForceSafeFrame(forceSafeFrame: boolean): Slot
Please keep the following things in mind while using this API:
- This setting will only take effect for subsequent ad requests made for the respective slots.
- The slot level setting, if specified, will always override the page level setting.
- If set to
true
(at slot-level or page level), the ad will always be rendered using a SafeFrame container independent of the choice made in the Google Ad Manager UI. - However, if set to
false
or left unspecified, the ad will be rendered using a SafeFrame container depending on the type of creative and the selection made in the Google Ad Manager UI. - This API should be used with caution as it could impact the behaviour of creatives that attempt to break out of their iFrames or rely on them being rendered directly in a publishers page.
- Example
JavaScript
googletag .defineSlot("/1234567/sports", [160, 600], "div") .setForceSafeFrame(true) .addService(googletag.pubads());
JavaScript (legacy)
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());
- See also
Parameters | |
---|---|
forceSafeFrame: boolean | true to force all ads in this slot to be rendered in SafeFrames and false to opt-out of a page-level setting (if present). Setting this to false when not specified at the page-level won't change anything. |
Returns | |
---|---|
Slot | The slot object on which the method was called. |
setSafeFrameConfig
setSafeFrameConfig(config: null | SafeFrameConfig): Slot
These slot-level preferences, if specified, will override any page-level preferences.
- Example
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 (legacy)
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");
- See also
Parameters | |
---|---|
config: null | SafeFrameConfig | The configuration object. |
Returns | |
---|---|
Slot | The slot object on which the method was called. |
setTargeting
setTargeting(key: string, value: string | string[]): Slot
- Example
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 (legacy)
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"]);
- See also
Parameters | |
---|---|
key: string | Targeting parameter key. |
value: string | string[] | Targeting parameter value or array of values. |
Returns | |
---|---|
Slot | The slot object on which the method was called. |
updateTargetingFromMap
updateTargetingFromMap(map: {
[adUnitPath: string]: string | string[];
}): Slot
Notes:
- In case of overwriting, only the last value will be kept.
- If the value is an array, any previous value will be overwritten, not merged.
- Values set here will overwrite targeting parameters set at the service-level.
- Example
JavaScript
const slot = googletag.defineSlot("/1234567/sports", [160, 600], "div"); slot.updateTargetingFromMap({ color: "red", interests: ["sports", "music", "movies"], });
JavaScript (legacy)
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"], });
Parameters | |
---|---|
map: { | Targeting parameter key:value map. |
Returns | |
---|---|
Slot | The slot object on which the method was called. |
googletag.config
Interfaces | |
---|---|
Ad | Settings to control ad expansion. |
Component | An object representing a single component auction in a on-device ad auction. |
Interstitial | An object which defines the behavior of a single interstitial ad slot. |
Page | Main configuration interface for page-level settings. |
Privacy | Settings to control publisher privacy treatments. |
Publisher | Publisher provided signals (PPS) configuration object. |
Slot | Main configuration interface for slot-level settings. |
Taxonomy | An object containing the values for a single Taxonomy. |
Type Aliases | |
---|---|
Interstitial | Supported interstitial ad triggers. |
Privacy | Supported publisher privacy treatments. |
Taxonomy | Supported taxonomies for publisher provided signals (PPS). |
Type Aliases
InterstitialTrigger
InterstitialTrigger: "unhideWindow" | "navBar"
PrivacyTreatment
PrivacyTreatment: "disablePersonalization"
Taxonomy
Taxonomy: "IAB_AUDIENCE_1_1" | "IAB_CONTENT_2_2"
googletag.config.AdExpansionConfig
Properties | |
---|---|
enabled | Whether ad expansion is enabled or disabled. |
- Example
JavaScript
// Enable ad slot expansion across the entire page. googletag.setConfig({ adExpansion: { enabled: true }, });
JavaScript (legacy)
// 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 }, });
Properties
Optional
enabled
enabled?: null | boolean
Setting this value overrides the default configured in Google Ad Manager.
googletag.config.ComponentAuctionConfig
Properties | |
---|---|
auction | An auction configuration object for this component auction. |
config | The configuration key associated with this component auction. |
Properties
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;
}
If this value is set to
null
, any existing configuration for the specified configKey
will be deleted.- Example
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 (legacy)
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
This value must be non-empty and should be unique. If two
ComponentAuctionConfig
objects share the same configKey value, the last to be set will overwrite prior configurations.googletag.config.InterstitialConfig
Properties | |
---|---|
require | Whether local storage consent is required to display this interstitial ad. |
triggers | The interstitial trigger configuration for this interstitial ad. |
Properties
Optional
requireStorageAccess
requireStorageAccess?: null | boolean
GPT uses local storage to enforce a frequency cap for interstitial ads. However, users who have not provided local storage consent are still eligible to be served interstitial ads. Setting this property to
true
opts out of the default behavior, and ensures interstial ads are only shown to users who have provided local storage consent.- Example
JavaScript
// Opt out of showing interstitials to users // without local storage consent. const interstitialSlot = googletag.defineOutOfPageSlot( "/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL, ); interstitialSlot.setConfig({ interstitial: { requireStorageAccess: true, // defaults to false }, });
JavaScript (legacy)
// Opt out of showing interstitials to users // without local storage consent. var interstitialSlot = googletag.defineOutOfPageSlot( "/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL, ); interstitialSlot.setConfig({ interstitial: { requireStorageAccess: true, // defaults to false }, });
TypeScript
// Opt out of showing interstitials to users // without local storage consent. const interstitialSlot = googletag.defineOutOfPageSlot( "/1234567/sports", googletag.enums.OutOfPageFormat.INTERSTITIAL, )!; interstitialSlot.setConfig({ interstitial: { requireStorageAccess: true, // defaults to false }, });
- See also
Optional
triggers
triggers?: null | Partial<Record<InterstitialTrigger, boolean>>
Setting the value of an interstitial trigger to
true
will enable it and false
will disable it. This will override the default values configured in Google Ad Manager.- Example
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 (legacy)
// 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, }, }, });
- See also
googletag.config.PageSettingsConfig
Allows setting multiple features with a single API call.
All properties listed below are examples and do not reflect actual features that utilize setConfig. For the set of features, see fields within the PageSettingsConfig type below.
Examples:
- Only features specified in the googletag.setConfig call are modified.
// Configure feature alpha. googletag.setConfig({ alpha: {...} }); // Configure feature bravo. Feature alpha is unchanged. googletag.setConfig({ bravo: {...} });
- All settings for a given feature are updated with each call to googletag.setConfig.
// Configure feature charlie to echo = 1, foxtrot = true. googletag.setConfig({ charlie: { echo: 1, foxtrot: true, } }); // Update feature charlie to echo = 2. Since foxtrot was not specified, // the value is cleared. googletag.setConfig({ charlie: { echo: 2 } });
- All settings for a feature can be cleared by passing
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, });
Properties | |
---|---|
ad | Settings to control ad expansion. |
ad | Deprecated. |
pps | Settings to control publisher provided signals (PPS). |
privacy | Settings to control publisher privacy treatments. |
thread | Setting to control whether GPT should yield the JS thread when rendering creatives. |
Properties
Optional
adExpansion
adExpansion?: null | AdExpansionConfig
Optional
adYield
adYield?: null | "DISABLED" | "ENABLED_ALL_SLOTS"
Optional
pps
pps?: null | PublisherProvidedSignalsConfig
Optional
privacyTreatments
privacyTreatments?: null | PrivacyTreatmentsConfig
Optional
threadYield
threadYield?: null | "DISABLED" | "ENABLED_ALL_SLOTS"
GPT will yield only for browsers that support the Scheduler.postTask or Scheduler.yield API.
Supported values:
null
(default): GPT will yield the JS thread for slots outside of the viewport.ENABLED_ALL_SLOTS
: GPT will yield the JS thread for all slots regardless of whether the slot is within the viewport.DISABLED
: GPT will not yield the JS thread.
- Example
JavaScript
// Disable yielding. googletag.setConfig({ threadYield: "DISABLED" }); // Enable yielding for all slots. googletag.setConfig({ threadYield: "ENABLED_ALL_SLOTS" }); // Enable yielding only for slots outside of the viewport (default). googletag.setConfig({ threadYield: null });
JavaScript (legacy)
// Disable yielding. googletag.setConfig({ threadYield: "DISABLED" }); // Enable yielding for all slots. googletag.setConfig({ threadYield: "ENABLED_ALL_SLOTS" }); // Enable yielding only for slots outside of the viewport (default). googletag.setConfig({ threadYield: null });
TypeScript
// Disable yielding. googletag.setConfig({ threadYield: "DISABLED" }); // Enable yielding for all slots. googletag.setConfig({ threadYield: "ENABLED_ALL_SLOTS" }); // Enable yielding only for slots outside of the viewport (default). googletag.setConfig({ threadYield: null });
- See also
googletag.config.PrivacyTreatmentsConfig
Properties | |
---|---|
treatments | An array of publisher privacy treatments to enable. |
Properties
treatments
treatments: null | "disablePersonalization"[]
- Example
JavaScript
// Disable personalization across the entire page. googletag.setConfig({ privacyTreatments: { treatments: ["disablePersonalization"] }, });
JavaScript (legacy)
// Disable personalization across the entire page. googletag.setConfig({ privacyTreatments: { treatments: ["disablePersonalization"] }, });
TypeScript
// Disable personalization across the entire page. googletag.setConfig({ privacyTreatments: { treatments: ["disablePersonalization"] }, });
googletag.config.PublisherProvidedSignalsConfig
Properties | |
---|---|
taxonomies | An object containing Taxonomy mappings. |
- Example
JavaScript
googletag.setConfig({ pps: { taxonomies: { IAB_AUDIENCE_1_1: { values: ["6", "626"] }, // '6' = 'Demographic | Age Range | 30-34' // '626' = 'Interest | Sports | Darts' IAB_CONTENT_2_2: { values: ["48", "127"] }, // '48' = 'Books and Literature | Fiction' // '127' = 'Careers | Job Search' }, }, });
JavaScript (legacy)
googletag.setConfig({ pps: { taxonomies: { IAB_AUDIENCE_1_1: { values: ["6", "626"] }, // '6' = 'Demographic | Age Range | 30-34' // '626' = 'Interest | Sports | Darts' IAB_CONTENT_2_2: { values: ["48", "127"] }, // '48' = 'Books and Literature | Fiction' // '127' = 'Careers | Job Search' }, }, });
TypeScript
googletag.setConfig({ pps: { taxonomies: { IAB_AUDIENCE_1_1: { values: ["6", "626"] }, // '6' = 'Demographic | Age Range | 30-34' // '626' = 'Interest | Sports | Darts' IAB_CONTENT_2_2: { values: ["48", "127"] }, // '48' = 'Books and Literature | Fiction' // '127' = 'Careers | Job Search' }, }, });
Properties
taxonomies
taxonomies: Partial<Record<Taxonomy, TaxonomyData>>
googletag.config.SlotSettingsConfig
Allows setting multiple features with a single API call for a single slot.
All properties listed below are examples and do not reflect actual features that utilize setConfig. For the set of features, see fields within the SlotSettingsConfig type below.
Examples:
- Only features specified in the Slot.setConfig call are modified.
const slot = googletag.defineSlot("/1234567/example", [160, 600]); // Configure feature alpha. slot.setConfig({ alpha: {...} }); // Configure feature bravo. Feature alpha is unchanged. slot.setConfig({ bravo: {...} });
- All settings for a given feature are updated with each call to 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 } });
- All settings for a feature can be cleared by passing
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, });
Properties | |
---|---|
ad | Settings to control ad expansion. |
component | An array of component auctions to be included in an on-device ad auction. |
interstitial | Settings that control interstitial ad slot behavior. |
Properties
Optional
adExpansion
adExpansion?: null | AdExpansionConfig
Optional
componentAuction
componentAuction?: null | ComponentAuctionConfig[]
Optional
interstitial
interstitial?: null | InterstitialConfig
googletag.config.TaxonomyData
Properties | |
---|---|
values | A list of Taxonomy values. |
Properties
values
values: string[]
googletag.enums
Enumerations | |
---|---|
Out | Out-of-page formats supported by GPT. |
Traffic | Traffic sources supported by GPT. |
Enumerations
OutOfPageFormat
OutOfPageFormat
- See also
TrafficSource
TrafficSource
Enumeration Members | |
---|---|
ORGANIC | Direct URL entry, site search, or app download. |
PURCHASED | Traffic redirected from properties other than owned (acquired or otherwise incentivized activity). |
googletag.events
Interfaces | |
---|---|
Event | Base Interface for all GPT events. |
Event | This is a pseudo-type that maps an event name to its corresponding event object type for Service.addEventListener and Service.removeEventListener. |
Game | This event is fired when a game manual interstitial slot has been closed by the user. |
Game | This event is fired when a game manual interstitial slot is ready to be shown to the user. |
Impression | This event is fired when an impression becomes viewable, according to the Active View criteria. |
Rewarded | This event is fired when a rewarded ad slot is closed by the user. |
Rewarded | This event is fired when a reward is granted for viewing a rewarded ad. |
Rewarded | This event is fired when a rewarded ad is ready to be displayed. |
Slot | This event is fired when the creative's iframe fires its load event. |
Slot | This event is fired when the creative code is injected into a slot. |
Slot | This event is fired when an ad has been requested for a particular slot. |
Slot | This event is fired when an ad response has been received for a particular slot. |
Slot | This event is fired whenever the on-screen percentage of an ad slot's area changes. |
googletag.events.Event
Properties | |
---|---|
service | Name of the service that triggered the event. |
slot | The slot that triggered the event. |
- See also
Properties
serviceName
serviceName: string
slot
slot: Slot
googletag.events.EventTypeMap
Properties
gameManualInterstitialSlotClosed
gameManualInterstitialSlotClosed: GameManualInterstitialSlotClosedEvent
gameManualInterstitialSlotReady
gameManualInterstitialSlotReady: GameManualInterstitialSlotReadyEvent
impressionViewable
impressionViewable: ImpressionViewableEvent
rewardedSlotClosed
rewardedSlotClosed: RewardedSlotClosedEvent
rewardedSlotGranted
rewardedSlotGranted: RewardedSlotGrantedEvent
rewardedSlotReady
rewardedSlotReady: RewardedSlotReadyEvent
slotOnload
slotOnload: SlotOnloadEvent
slotRenderEnded
slotRenderEnded: SlotRenderEndedEvent
slotRequested
slotRequested: SlotRequestedEvent
slotResponseReceived
slotResponseReceived: SlotResponseReceived
slotVisibilityChanged
slotVisibilityChanged: SlotVisibilityChangedEvent
googletag.events.GameManualInterstitialSlotClosedEvent
ExtendsNote: Game manual interstitial is a limited-access format.
Properties | |
---|---|
service | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Example
JavaScript
// This listener is called when a game manual interstitial slot is closed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotClosed", (event) => { const slot = event.slot; console.log("Game manual interstital slot", slot.getSlotElementId(), "is closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (legacy)
// This listener is called when a game manual interstitial slot is closed. var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotClosed", function (event) { var slot = event.slot; console.log("Game manual interstital slot", slot.getSlotElementId(), "is closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
// This listener is called when a game manual interstitial slot is closed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotClosed", (event) => { const slot = event.slot; console.log("Game manual interstital slot", slot.getSlotElementId(), "is closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
googletag.events.GameManualInterstitialSlotReadyEvent
ExtendsNote: Game manual interstitial is a limited-access format.
Properties | |
---|---|
service | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
Methods | |
---|---|
make | Displays the game manual interstitial ad to the user. |
- Example
JavaScript
// This listener is called when a game manual interstitial slot is ready to // be displayed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotReady", (event) => { const slot = event.slot; console.log( "Game manual interstital slot", slot.getSlotElementId(), "is ready to be displayed.", ); // Replace with custom logic. const displayGmiAd = true; if (displayGmiAd) { event.makeGameManualInterstitialVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (legacy)
// This listener is called when a game manual interstitial slot is ready to // be displayed. var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotReady", function (event) { var slot = event.slot; console.log( "Game manual interstital slot", slot.getSlotElementId(), "is ready to be displayed.", ); // Replace with custom logic. var displayGmiAd = true; if (displayGmiAd) { event.makeGameManualInterstitialVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
// This listener is called when a game manual interstitial slot is ready to // be displayed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL, ); // Slot returns null if the page or device does not support game manual interstitial ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); googletag.pubads().addEventListener("gameManualInterstitialSlotReady", (event) => { const slot = event.slot; console.log( "Game manual interstital slot", slot.getSlotElementId(), "is ready to be displayed.", ); // Replace with custom logic. const displayGmiAd = true; if (displayGmiAd) { event.makeGameManualInterstitialVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
Methods
makeGameManualInterstitialVisible
makeGameManualInterstitialVisible(): void
googletag.events.ImpressionViewableEvent
ExtendsProperties | |
---|---|
service | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Example
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 (legacy)
// 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. } });
- See also
googletag.events.RewardedSlotClosedEvent
ExtendsProperties | |
---|---|
service | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Example
JavaScript
const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called when the user closes a rewarded ad slot. googletag.pubads().addEventListener("rewardedSlotClosed", (event) => { const slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "has been closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (legacy)
var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called when the user closes a rewarded ad slot. googletag.pubads().addEventListener("rewardedSlotClosed", function (event) { var slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "has been closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called when the user closes a rewarded ad slot. googletag.pubads().addEventListener("rewardedSlotClosed", (event) => { const slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "has been closed."); if (slot === targetSlot) { // Slot specific logic. } }); }
- See also
googletag.events.RewardedSlotGrantedEvent
ExtendsProperties | |
---|---|
payload | An object containing information about the reward that was granted. |
service | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Example
JavaScript
const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotGranted", (event) => { const slot = event.slot; console.group("Reward granted for slot", slot.getSlotElementId(), "."); // Log details of the reward. console.log("Reward type:", event.payload?.type); console.log("Reward amount:", event.payload?.amount); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (legacy)
var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotGranted", function (event) { var _a, _b; var slot = event.slot; console.group("Reward granted for slot", slot.getSlotElementId(), "."); // Log details of the reward. console.log("Reward type:", (_a = event.payload) === null || _a === void 0 ? void 0 : _a.type); console.log( "Reward amount:", (_b = event.payload) === null || _b === void 0 ? void 0 : _b.amount, ); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotGranted", (event) => { const slot = event.slot; console.group("Reward granted for slot", slot.getSlotElementId(), "."); // Log details of the reward. console.log("Reward type:", event.payload?.type); console.log("Reward amount:", event.payload?.amount); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } }); }
- See also
Properties
payload
payload: null | RewardedPayload
googletag.events.RewardedSlotReadyEvent
ExtendsProperties | |
---|---|
service | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
Methods | |
---|---|
make | Displays the rewarded ad. |
- Example
JavaScript
// This listener is called when a rewarded ad slot becomes ready to be // displayed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotReady", (event) => { const slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed."); // Replace with custom logic. const userHasConsented = true; if (userHasConsented) { event.makeRewardedVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
JavaScript (legacy)
// This listener is called when a rewarded ad slot becomes ready to be // displayed. var targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotReady", function (event) { var slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed."); // Replace with custom logic. var userHasConsented = true; if (userHasConsented) { event.makeRewardedVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
TypeScript
// This listener is called when a rewarded ad slot becomes ready to be // displayed. const targetSlot = googletag.defineOutOfPageSlot( "/1234567/example", googletag.enums.OutOfPageFormat.REWARDED, ); // Slot returns null if the page or device does not support rewarded ads. if (targetSlot) { targetSlot.addService(googletag.pubads()); // This listener is called whenever a reward is granted for a // rewarded ad. googletag.pubads().addEventListener("rewardedSlotReady", (event) => { const slot = event.slot; console.log("Rewarded ad slot", slot.getSlotElementId(), "is ready to be displayed."); // Replace with custom logic. const userHasConsented = true; if (userHasConsented) { event.makeRewardedVisible(); } if (slot === targetSlot) { // Slot specific logic. } }); }
- See also
Methods
makeRewardedVisible
makeRewardedVisible(): void
googletag.events.SlotOnloadEvent
ExtendsSlotOnloadEvent
will be fired.Properties | |
---|---|
service | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Example
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 (legacy)
// 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. } });
- See also
googletag.events.SlotRenderEndedEvent
ExtendsProperties | |
---|---|
advertiser | Advertiser ID of the rendered ad. |
campaign | Campaign ID of the rendered ad. |
company | IDs of the companies that bid on the rendered backfill ad. |
creative | Creative ID of the rendered reservation ad. |
creative | Creative template ID of the rendered reservation ad. |
is | Whether an ad was a backfill ad. |
is | Whether an ad was returned for the slot. |
label | Deprecated. |
line | Line item ID of the rendered reservation ad. |
service | Name of the service that triggered the event. Inherited from |
size | Indicates the pixel size of the rendered creative. |
slot | The slot that triggered the event. Inherited from |
slot | Whether the slot content was changed with the rendered ad. |
source | Creative ID of the rendered reservation or backfill ad. |
source | Line item ID of the rendered reservation or backfill ad. |
yield | IDs of the yield groups for the rendered backfill ad. |
- Example
JavaScript
// This listener is called when a slot has finished rendering. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRenderEnded", (event) => { const slot = event.slot; console.group("Slot", slot.getSlotElementId(), "finished rendering."); // Log details of the rendered ad. console.log("Advertiser ID:", event.advertiserId); console.log("Campaign ID:", event.campaignId); console.log("Company IDs:", event.companyIds); console.log("Creative ID:", event.creativeId); console.log("Creative Template ID:", event.creativeTemplateId); console.log("Is backfill?:", event.isBackfill); console.log("Is empty?:", event.isEmpty); console.log("Line Item ID:", event.lineItemId); console.log("Size:", event.size); console.log("Slot content changed?", event.slotContentChanged); console.log("Source Agnostic Creative ID:", event.sourceAgnosticCreativeId); console.log("Source Agnostic Line Item ID:", event.sourceAgnosticLineItemId); console.log("Yield Group IDs:", event.yieldGroupIds); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
JavaScript (legacy)
// This listener is called when a slot has finished rendering. var targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRenderEnded", function (event) { var slot = event.slot; console.group("Slot", slot.getSlotElementId(), "finished rendering."); // Log details of the rendered ad. console.log("Advertiser ID:", event.advertiserId); console.log("Campaign ID:", event.campaignId); console.log("Company IDs:", event.companyIds); console.log("Creative ID:", event.creativeId); console.log("Creative Template ID:", event.creativeTemplateId); console.log("Is backfill?:", event.isBackfill); console.log("Is empty?:", event.isEmpty); console.log("Line Item ID:", event.lineItemId); console.log("Size:", event.size); console.log("Slot content changed?", event.slotContentChanged); console.log("Source Agnostic Creative ID:", event.sourceAgnosticCreativeId); console.log("Source Agnostic Line Item ID:", event.sourceAgnosticLineItemId); console.log("Yield Group IDs:", event.yieldGroupIds); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
TypeScript
// This listener is called when a slot has finished rendering. const targetSlot = googletag.defineSlot("/1234567/example", [160, 600]); googletag.pubads().addEventListener("slotRenderEnded", (event) => { const slot = event.slot; console.group("Slot", slot.getSlotElementId(), "finished rendering."); // Log details of the rendered ad. console.log("Advertiser ID:", event.advertiserId); console.log("Campaign ID:", event.campaignId); console.log("Company IDs:", event.companyIds); console.log("Creative ID:", event.creativeId); console.log("Creative Template ID:", event.creativeTemplateId); console.log("Is backfill?:", event.isBackfill); console.log("Is empty?:", event.isEmpty); console.log("Line Item ID:", event.lineItemId); console.log("Size:", event.size); console.log("Slot content changed?", event.slotContentChanged); console.log("Source Agnostic Creative ID:", event.sourceAgnosticCreativeId); console.log("Source Agnostic Line Item ID:", event.sourceAgnosticLineItemId); console.log("Yield Group IDs:", event.yieldGroupIds); console.groupEnd(); if (slot === targetSlot) { // Slot specific logic. } });
- See also
Properties
advertiserId
advertiserId: null | number
null
for empty slots, backfill ads, and creatives rendered by services other than PubAdsService.campaignId
campaignId: null | number
null
for empty slots, backfill ads, and creatives rendered by services other than PubAdsService.companyIds
companyIds: null | number[]
null
for empty slots, reservation ads, and creatives rendered by services other than PubAdsService.creativeId
creativeId: null | number
null
for empty slots, backfill ads, and creatives rendered by services other than PubAdsService.creativeTemplateId
creativeTemplateId: null | number
null
for empty slots, backfill ads, and creatives rendered by services other than PubAdsService.isBackfill
isBackfill: boolean
true
if the ad was a backfill ad, false
otherwise.isEmpty
isEmpty: boolean
true
if no ad was returned, false
otherwise.labelIds
labelIds: null | number[]
lineItemId
lineItemId: null | number
null
for empty slots, backfill ads, and creatives rendered by services other than PubAdsService.size
size: null | string | number[]
[728, 90]
. Value is null
for empty ad slots.slotContentChanged
slotContentChanged: boolean
true
if the content was changed, false
otherwise.sourceAgnosticCreativeId
sourceAgnosticCreativeId: null | number
null
if the ad is not a reservation or line item backfill, or the creative is rendered by services other than PubAdsService.sourceAgnosticLineItemId
sourceAgnosticLineItemId: null | number
null
if the ad is not a reservation or line item backfill, or the creative is rendered by services other than PubAdsService.yieldGroupIds
yieldGroupIds: null | number[]
null
for empty slots, reservation ads, and creatives rendered by services other than PubAdsService.googletag.events.SlotRequestedEvent
ExtendsProperties | |
---|---|
service | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Example
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 (legacy)
// 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. } });
- See also
googletag.events.SlotResponseReceived
ExtendsProperties | |
---|---|
service | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Example
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 (legacy)
// 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. } });
- See also
googletag.events.SlotVisibilityChangedEvent
ExtendsProperties | |
---|---|
in | The percentage of the ad's area that is visible. |
service | Name of the service that triggered the event. Inherited from |
slot | The slot that triggered the event. Inherited from |
- Example
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 (legacy)
// 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. } });
- See also
Properties
inViewPercentage
inViewPercentage: number
googletag.secureSignals
Interfaces | |
---|---|
Bidder | Returns a secure signal for a specific bidder. |
Publisher | Returns a secure signal for a specific publisher. |
Secure | An interface for managing secure signals. |
Type Aliases | |
---|---|
Secure | Interface for returning a secure signal for a specific bidder or provider. |
Type Aliases
SecureSignalProvider
SecureSignalProvider: BidderSignalProvider | PublisherSignalProvider
id
or networkCode
must be provided, but not both.googletag.secureSignals.BidderSignalProvider
A bidder secure signal provider consists of 2 parts:
- A collector function, which returns a
Promise
that resolves to a secure signal. - An
id
which identifies the bidder associated with the signal.
Properties | |
---|---|
collector | A function which returns a Promise that resolves to a secure signal. |
id | A unique identifier for the collector associated with this secure signal, as registered in Google Ad Manager. |
- Example
JavaScript
// id is provided googletag.secureSignalProviders.push({ id: "collector123", collectorFunction: () => { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
JavaScript (legacy)
// 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"); }, });
Properties
collectorFunction
collectorFunction: (() => Promise<string>)
Promise
that resolves to a secure signal.id
id: string
googletag.secureSignals.PublisherSignalProvider
A publisher signal provider consists of 2 parts:
- A collector function, which returns a
Promise
that resolves to a secure signal. - A
networkCode
which identifies the publisher associated with the signal.
Properties | |
---|---|
collector | A function which returns a Promise that resolves to a secure signal. |
network | The network code (as seen in the ad unit path) for the publisher associated with this secure signal. |
- Example
JavaScript
// networkCode is provided googletag.secureSignalProviders.push({ networkCode: "123456", collectorFunction: () => { // ...custom signal generation logic... return Promise.resolve("signal"); }, });
JavaScript (legacy)
// 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"); }, });
Properties
collectorFunction
collectorFunction: (() => Promise<string>)
Promise
that resolves to a secure signal.networkCode
networkCode: string
googletag.secureSignals.SecureSignalProvidersArray
Methods | |
---|---|
clear | Clears all signals for all collectors from cache. |
push | Adds a new secureSignals.SecureSignalProvider to the signal provider array and begins the signal generation process. |
Methods
clearAllCache
clearAllCache(): void
Calling this method may reduce the likelihood of signals being included in ad requests for the current and potentially later page views. Due to this, it should only be called when meaningful state changes occur, such as events that indicate a new user (log in, log out, sign up, etc.).
push
push(provider: SecureSignalProvider): void
Parameters | |
---|---|
provider: SecureSignalProvider | The secureSignals.SecureSignalProvider object to be added to the array. |