GPT Reference

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


Type Definitions

Types
SingleSize | MultiSize
SingleSize[]
string | string[]

Named sizes that a slot can have. In most cases size is a fixed-size rectangle but there are some cases when we need other kinds of size specifications. Only the following are valid named sizes:

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

SingleSizeArray | NamedSize
number[]

Array of two numbers representing [width, height].

GeneralSize[]
SizeMapping[]

Enum Types

Enums
googletag.enums.OutOfPageFormat
Out of page formats supported by GPT.


googletag.enums.OutOfPageFormat

Values
BOTTOM_ANCHOR
Anchor format where slot sticks to the bottom of the viewport.
INTERSTITIAL
Web interstitial creative format.
TOP_ANCHOR
Anchor format where slot sticks to the top of the viewport.


googletag

Variable Summary
apiReady
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.
pubadsReady
Flag indicating that PubAdsService is enabled, loaded and fully operational.
Function Summary
companionAds
Returns a reference to the CompanionAdsService.
content
Returns a reference to the ContentService.
defineOutOfPageSlot
Constructs an out-of-page (interstitial) ad slot with the given ad unit path.
defineSlot
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.
destroySlots
Destroys the given slots, removing all related objects and references of those slots from GPT.
disablePublisherConsole
Disables the Google Publisher Console.
display
Instructs slot services to render the slot.
enableServices
Enables all GPT services that have been defined for ad slots on the page.
getVersion
Returns the current version of GPT.
openConsole
Opens the Google Publisher Console.
pubads
Returns a reference to the PubAdsService.
setAdIframeTitle
Sets the title for all ad container iframes created by PubAdsService, from this point onwards.
sizeMapping
Creates a new SizeMappingBuilder.


googletag.apiReady

  • apiReady: boolean | undefined
  • Flag indicating that the GPT API is loaded and ready to be called. This property will be simply 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.

  • Example
    <script>
      if (window.googletag && googletag.apiReady) {
        // GPT API can be called safely.
      }
    </script>


googletag.cmd

  • cmd: Array<() => void> | CommandArray
  • Reference to the global command queue for asynchronous execution of GPT-related calls.

    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
    googletag.cmd.push(function() {
      googletag.defineSlot('/1234567/sports', [160, 600])
               .addService(googletag.pubads());
    });


googletag.pubadsReady


googletag.companionAds


googletag.content


googletag.defineOutOfPageSlot

  • defineOutOfPageSlot(adUnitPath: string, div?: string | OutOfPageFormat): Slot
  • Constructs an out-of-page (interstitial) ad slot with the given ad unit path.

    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. See the article on web interstitials for more details.

  • Example
    // 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);
  • Parameters
    adUnitPath: string
    Full ad unit path with the network code and ad unit code.
    div?: string | OutOfPageFormat
    ID of the div that will contain this ad unit or OutOfPageFormat.
  • Returns
    Slot
    The newly created slot.


googletag.defineSlot

  • defineSlot(adUnitPath: string, size: GeneralSize, div?: string): Slot
  • 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.

  • Example
    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.
    div?: string
    ID of the div that will contain this ad unit.
  • Returns
    Slot
    The newly created slot.


googletag.destroySlots

  • destroySlots(slots?: Slot[]): boolean
  • Destroys the given slots, removing all related objects and references of those slots from GPT. This API does not support passback slots and companion slots.

    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
    // The calls to construct an ad and display contents.
    var slot1 =
        googletag.pubads().display('/1234567/sports', [728, 90], 'div-1');
    var slot2 =
        googletag.pubads().display('/1234567/news', [160, 600], 'div-2');
    var slot3 =
        googletag.pubads().display('/1234567/weather', [160, 600], 'div-3');
    
    // 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
    slots?: Slot[]
    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.


googletag.disablePublisherConsole

  • disablePublisherConsole(): void
  • Disables the Google Publisher Console. See the Google Publisher Console guide for more details.


googletag.display

  • display(divOrSlot: string | Element | Slot): void
  • Instructs slot services to render the slot. Each ad slot should only be displayed once per page. All slots must be defined and have a service associated with them before being displayed. The display call must not happen until the element is present in the DOM. The usual way to achieve that is to place it within a script block within the div element named in the method call.

    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.

  • Example
    <div id="div-1" style="width: 728px; height: 90px">
      <script type="text/javascript">
        googletag.cmd.push(function() {
          googletag.display('div-1');
        });
      </script>
    </div>
  • 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 googletag.defineSlot().


googletag.enableServices

  • enableServices(): void
  • Enables all GPT services that have been defined for ad slots on the page.


googletag.getVersion

  • getVersion(): string
  • Returns the current version of GPT.

  • Learn more about GPT versions in the GPT version history.

  • Returns
    string
    The currently executing GPT version string.


googletag.openConsole

  • openConsole(div?: string): void
  • Opens the Google Publisher Console. See the Google Publisher Console guide for more details.

  • Example
    // Calling with div ID.
    googletag.openConsole('div-1');
    
    // Calling without div ID.
    googletag.openConsole();
  • Parameters
    div?: string
    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.


googletag.pubads


googletag.setAdIframeTitle

  • setAdIframeTitle(title: string): void
  • Sets the title for all ad container iframes created by PubAdsService, from this point onwards.

  • Example
    googletag.setAdIframeTitle('title');
  • Parameters
    title: string
    The new title for all ad container iframes.


googletag.sizeMapping


googletag.CommandArray

The command array accepts a sequence of functions and invokes them in order. It is intended to replace a standard array that is used to enqueue functions to be invoked once GPT is loaded.

Method Summary
push
Executes the sequence of functions specified in the arguments in order.


push

  • push(...f: Array<() => void>): number
  • Executes the sequence of functions specified in the arguments in order.

  • Example
    googletag.cmd.push(function() {
      googletag.defineSlot('/1234567/sports', [160, 600])
               .addService(googletag.pubads());
    });
  • Parameters
    ...f: Array<() => void>
    A JavaScript function to be executed.
  • 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

Extends Service

Companion Ads service. This service is used by video ads to show companion ads. See the article on companion ads for video for more details.

Method Summary
addEventListener
Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page.
getSlots
Get the list of slots associated with this service.
removeEventListener
Removes a previously registered listener.
setRefreshUnfilledSlots
Sets whether companion slots that have not been filled will be automatically backfilled.


setRefreshUnfilledSlots

  • setRefreshUnfilledSlots(value: boolean): void
  • Sets whether companion slots that have not been filled will be automatically backfilled.

    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
    googletag.companionAds().setRefreshUnfilledSlots(true);
  • Parameters
    value: boolean
    true to automatically backfill unfilled slots, false to leave them unchanged.


googletag.ContentService

Extends Service

The content service. This service is used to set the content of a slot manually.

Method Summary
addEventListener
Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page.
getSlots
Get the list of slots associated with this service.
removeEventListener
Removes a previously registered listener.
setContent
Fills a slot with the given content.


setContent

  • setContent(slot: Slot, content: string): void
  • Fills a slot with the given content. If services are not yet enabled, stores the content and fills it in when services are enabled.

  • Example
    var slot = googletag.defineSlot('/1234567/sports', [728, 90], 'div-1')
                        .addService(googletag.content());
    googletag.enableServices();
    
    var content = '<a href="www.mydestinationsite.com">' +
                  '<img src="www.mysite.com/img.png">' +
                  '</img></a>';
    googletag.content().setContent(slot, content);
  • Parameters
    slot: Slot
    The slot to be filled.
    content: string
    The HTML content for the slot.


googletag.PrivacySettingsConfig

Configuration object for privacy settings.

Property Summary
childDirectedTreatment
Indicates whether the page should be treated as child-directed.
limitedAds
Enables serving to run in limited ads mode to aid in publisher regulatory compliance needs.
nonPersonalizedAds
Enables serving to run in non-personalized ads mode to aid in publisher regulatory compliance needs.
restrictDataProcessing
Enables serving to run in restricted processing mode to aid in publisher regulatory compliance needs.
underAgeOfConsent
Indicates whether to mark ad requests as coming from users under the age of consent.


childDirectedTreatment

  • childDirectedTreatment: null | boolean
  • Indicates whether the page should be treated as child-directed. Set to null to clear the configuration.


limitedAds

  • limitedAds: boolean
  • Enables serving to run in limited ads mode to aid in publisher regulatory compliance needs. When enabled, the GPT library itself may optionally be requested from a cookie-less, limited ads URL.


nonPersonalizedAds

  • nonPersonalizedAds: boolean
  • Enables serving to run in non-personalized ads mode to aid in publisher regulatory compliance needs.


restrictDataProcessing

  • restrictDataProcessing: boolean
  • Enables serving to run in restricted processing mode to aid in publisher regulatory compliance needs.


underAgeOfConsent

  • underAgeOfConsent: null | boolean
  • Indicates whether to mark ad requests as coming from users under the age of consent. Set to null to clear the configuration.


googletag.PubAdsService

Extends Service

Publisher Ads service. This service is used to fetch and show ads from your Google Ad Manager account.

Method Summary
addEventListener
Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page.
clear
Removes the ads from the given slots and replaces them with blank content.
clearCategoryExclusions
Clears all page-level ad category exclusion labels.
clearTargeting
Clears custom targeting parameters for a specific key or for all keys.
collapseEmptyDivs
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.
disableInitialLoad
Disables requests for ads on page load, but allows ads to be requested with a googletag.pubads().refresh() call.
display
Constructs and displays an ad slot with the given ad unit path and size.
enableLazyLoad
Enables lazy loading in GPT as defined by the config object.
enableSingleRequest
Enables single request mode for fetching multiple ads at the same time.
enableVideoAds
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.
getAttributeKeys
Returns the attribute keys that have been set on this service.
getSlots
Get the list of slots associated with this service.
getTargeting
Returns a specific custom service-level targeting parameter that has been set.
getTargetingKeys
Returns the list of all custom service-level targeting keys that have been set.
isInitialLoadDisabled
Returns whether or not initial requests for ads was successfully disabled by a previous disableInitialLoad call.
refresh
Fetches and displays new ads for specific or all slots on the page.
removeEventListener
Removes a previously registered listener.
set
Sets values for AdSense attributes that apply to all ad slots under the Publisher Ads service.
setCategoryExclusion
Sets a page-level ad category exclusion for the given label name.
setCentering
Enables and disables horizontal centering of ads.
setCookieOptions
Sets options for ignoring Google Ad Manager cookies on the current page.
setForceSafeFrame
Configures whether all ads on the page should be forced to be rendered using a SafeFrame container.
setLocation
Passes location information from websites so you can geo-target line items to specific locations.
setPrivacySettings
Allows configuration of all privacy settings from a single API using a config object.
setPublisherProvidedId
Sets the value for the publisher-provided ID.
setRequestNonPersonalizedAds
Configures whether the page should request personalized or non-personalized ads.
setSafeFrameConfig
Sets the page-level preferences for SafeFrame configuration.
setTargeting
Sets custom targeting parameters for a given key that apply to all Publisher Ads service ad slots.
setVideoContent
Sets the video content information to be sent along with the ad requests for targeting and content exclusion purposes.
updateCorrelator
Changes the correlator that is sent with ad requests, effectively starting a new page view.


clear

  • clear(slots?: Slot[]): boolean
  • Removes the ads from the given slots and replaces them with blank content. The slots will be marked as unfetched.

    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
      // 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
    slots?: Slot[]
    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
  • Clears all page-level ad category exclusion labels. This is useful if you want to refresh the slot.

  • Example
    // 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.
  • Returns
    PubAdsService
    The service object on which the method was called.


clearTargeting

  • clearTargeting(key?: string): PubAdsService
  • Clears custom targeting parameters for a specific key or for all keys.

  • Example
    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.
  • Parameters
    key?: string
    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
  • 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. This mode must be set before the service is enabled. See the collapse empty ad slots sample for more details.

  • Parameters
    collapseBeforeAdFetch?: boolean
    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
  • Disables requests for ads on page load, but allows ads to be requested with a googletag.pubads().refresh() call. This should be set prior to enabling the service. Async mode must be used; otherwise it will be impossible to request ads using refresh.


display

  • display(adUnitPath: string, size: GeneralSize, div?: string | Element, clickUrl?: string): void
  • Constructs and displays an ad slot with the given ad unit path and size. This method does not work with single request mode.

    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
    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.
    div?: string | Element
    Either the ID of the div containing the slot or the div element itself.
    clickUrl?: string
    The click URL to use on this slot.


enableLazyLoad

  • enableLazyLoad(config: { fetchMarginPercent: number, mobileScaling: number, renderMarginPercent: number }): void
  • Enables lazy loading in GPT as defined by the config object. For more detailed examples, see the Lazy loading sample.

    Notes:

    • Lazy fetching in SRA only works if all slots are outside the fetching margin.

  • Example
    googletag.pubads().enableLazyLoad({
      fetchMarginPercent: 500,  // Fetch slots within 5 viewports.
      renderMarginPercent: 200,  // Render slots within 2 viewports.
      mobileScaling: 2.0  // Double the above values on mobile.
    });
  • Parameters
    config: { fetchMarginPercent: number, mobileScaling: number, renderMarginPercent: number }
    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.
    fetchMarginPercent
    The minimum distance from the current viewport a slot must be before we fetch the ad as a percentage of viewport size. A value of 0 means "when the slot enters the viewport", 100 means "when the ad is 1 viewport away", and so on.
    renderMarginPercent
    The minimum distance from the current viewport a slot must be before we render an ad. This allows for prefetching the ad, but waiting to render and download other subresources. The value works just like fetchMarginPercent as a percentage of viewport.
    mobileScaling
    A multiplier applied to margins on mobile devices. This allows varying margins on mobile vs. desktop. For example, a value of 2.0 will multiply all margins by 2 on mobile devices, increasing the minimum distance a slot can be before fetching and rendering.


enableSingleRequest

  • enableSingleRequest(): boolean
  • Enables single request mode for fetching multiple ads at the same time. This requires all Publisher Ads slots to be defined and added to the PubAdsService prior to enabling the service. Single request mode must be set before the service is enabled.

  • 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
  • Signals to GPT that video ads will be present on the page. This enables competitive exclusion constraints on display and video ads. If the video content is known, call setVideoContent in order to be able to use content exclusion for display ads.


get

  • get(key: string): null | string
  • Returns the value for the AdSense attribute associated with the given key.

  • Example
    googletag.pubads().set('adsense_background_color', '#FFFFFF');
    var color = googletag.pubads().get('adsense_background_color');
    // color == '#FFFFFF'.
  • 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[]
  • Returns the attribute keys that have been set on this service.

  • Example
    googletag.pubads().set('adsense_background_color', '#FFFFFF');
    googletag.pubads().set('adsense_border_color', '#AABBCC');
    var keys = googletag.pubads().getAttributeKeys();
    // Keys are ['adsense_background_color', 'adsense_border_color'].
  • Returns
    string[]
    Array of attribute keys set on this service. Ordering is undefined.


getTargeting

  • getTargeting(key: string): string[]
  • Returns a specific custom service-level targeting parameter that has been set.

  • Example
    googletag.pubads().setTargeting('interests', 'sports');
    
    var param = googletag.pubads().getTargeting('interests');
    // param is ['sports']
    
    var param = googletag.pubads().getTargeting('age');
    // param is [] (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[]
  • Returns the list of all custom service-level targeting keys that have been set.

  • Example
    googletag.pubads().setTargeting('interests', 'sports');
    googletag.pubads().setTargeting('colors', 'blue');
    
    var keys = googletag.pubads().getTargetingKeys();
    // keys are ['interests', 'colors'].
  • Returns
    string[]
    Array of targeting keys. Ordering is undefined.


isInitialLoadDisabled

  • isInitialLoadDisabled(): boolean
  • Returns whether or not initial requests for ads was successfully disabled by a previous disableInitialLoad call.

  • Returns
    boolean
    Returns true if a previous call to disableInitialLoad was successful, false otherwise.


refresh

  • refresh(slots?: null | Slot[], options?: { changeCorrelator: boolean }): void
  • Fetches and displays new ads for specific or all slots on the page. Works only in asynchronous rendering mode.

    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 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
      // 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
    slots?: null | Slot[]
    The slots to refresh. Array is optional; all slots will be refreshed if it is unspecified.
    options?: { changeCorrelator: boolean }
    Configuration options associated with this refresh call.
    changeCorrelator
    Specifies whether or not a new correlator is to be generated for fetching ads. Our ad servers maintain this correlator value briefly (currently for 30 seconds, but subject to change), such that requests with the same correlator received close together will be considered a single page view. By default a new correlator is generated for every refresh.

    Note: this option has no effect on GPT's long-lived pageview, which automatically reflects the ads currently on the page and has no expiration time.


set

  • set(key: string, value: string): PubAdsService
  • Sets values for AdSense attributes that apply to all ad slots under the Publisher Ads service.

    See AdSense Attributes for a list of available keys and values. 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
    googletag.pubads().set('adsense_background_color', '#FFFFFF');
  • 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
  • Sets a page-level ad category exclusion for the given label name.

    See the article on ad exclusion for more details.

  • Example
    // Label = AirlineAd.
    googletag.pubads().setCategoryExclusion('AirlineAd');
  • 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
  • Enables and disables horizontal centering of ads. Centering is disabled by default. In legacy gpt_mobile.js, centering is enabled by default.

  • This method should be invoked before calling display or refresh because only ads that are requested after calling this method will be centered.

  • Example
    // Make ads centered.
    googletag.pubads().setCentering(true);
  • Parameters
    centerAds: boolean
    true to center ads, false to left-align them.


setCookieOptions

  • setCookieOptions(options: number): PubAdsService
  • Sets options for ignoring Google Ad Manager cookies on the current page.

  • Example
    // Ignores Google Ad Manager cookies.
    googletag.pubads().setCookieOptions(1);
  • Parameters
    options: number
    The cookie options to set. Possible values are:
    • 0: Enables Google Ad Manager cookies on ad requests on the page. This option is set by default.
    • 1: Ignores Google Ad Manager cookies on subsequent ad requests and prevents cookies from being created on the page. Note that cookies will not be ignored on certain pingbacks and that this option will disable features that rely on cookies, such as dynamic allocation.
  • Returns
    PubAdsService
    The service object on which the method was called.


setForceSafeFrame

  • setForceSafeFrame(forceSafeFrame: boolean): PubAdsService
  • Configures whether all ads on the page should be forced to be rendered using a SafeFrame container. For more details, please see the article on rendering creatives using SafeFrame.

    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 (see related article).
    • 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
    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();
  • 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
  • Passes location information from websites so you can geo-target line items to specific locations.

  • Example
    // 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
  • Allows configuration of all privacy settings from a single API using a config object.

  • Example
    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
  • Sets the value for the publisher-provided ID. See the article on PPID for more details.

  • Example
    googletag.pubads().setPublisherProvidedId('AB123456789');
  • Parameters
    ppid: string
    An alphanumeric ID provided by the publisher with a recommended maximum of 150 characters.
  • Returns
    PubAdsService
    The service object on which the method was called.


setRequestNonPersonalizedAds

  • setRequestNonPersonalizedAds(nonPersonalizedAds: number): PubAdsService
  • Configures whether the page should request personalized or non-personalized ads. Personalized ads served by default.

  • Example
    // Mark ad requests to request non-personalized ads.
    googletag.pubads().setRequestNonPersonalizedAds(1);
  • Parameters
    nonPersonalizedAds: number
    0 for personalized ads, 1 for non-personalized ads.
  • Returns
    PubAdsService
    The service object on which the method was called.


setSafeFrameConfig

  • setSafeFrameConfig(config: SafeFrameConfig): PubAdsService
  • Sets the page-level preferences for SafeFrame configuration. Any unrecognized keys in the config object will be ignored. The entire config will be ignored if an invalid value is passed for a recognized key.

  • These page-level preferences will be overridden by slot-level preferences, if specified. For more details, please see the article on rendering creatives using SafeFrame.

  • Example
    googletag.pubads().setForceSafeFrame(true);
    
    var pageConfig = {
      allowOverlayExpansion: true,
      allowPushExpansion: true,
      sandbox: true,
      useUniqueDomain: 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();
  • 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
  • Sets custom targeting parameters for a given key that apply to all Publisher Ads service ad slots. Calling this multiple times for the same key will overwrite old values. These keys are defined in your Google Ad Manager account.

  • Example
    // 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']);
  • 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
  • Sets the video content information to be sent along with the ad requests for targeting and content exclusion purposes. Video ads will be automatically enabled when this method is called. For videoContentId and videoCmsId, use the values that are provided to the Google Ad Manager content ingestion service.

    See the article on video content for more details.

  • Parameters
    videoContentId: string
    The video content ID.
    videoCmsId: string
    The video CMS ID.


updateCorrelator

  • updateCorrelator(): PubAdsService
  • Changes the correlator that is sent with ad requests, effectively starting a new page view. The correlator is the same for all the ad requests coming from one page view, and unique across page views. Only applies to async mode.

  • 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
    // 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

An object representing a single ad response.

Property Summary
advertiserId
The ID of the advertiser.
campaignId
The ID of the campaign.
creativeId
The ID of the creative.
creativeTemplateId
The template ID of the ad.
lineItemId
The ID of the line item.


advertiserId

  • advertiserId: null | number
  • The ID of the advertiser.


campaignId

  • campaignId: null | number
  • The ID of the campaign.


creativeId

  • creativeId: null | number
  • The ID of the creative.


creativeTemplateId

  • creativeTemplateId: null | number
  • The template ID of the ad.


lineItemId

  • lineItemId: null | number
  • The ID of the line item.


googletag.SafeFrameConfig

Configuration object for SafeFrame containers.

Property Summary
allowOverlayExpansion
Whether SafeFrame should allow ad content to expand by overlaying page content.
allowPushExpansion
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.
useUniqueDomain
Whether SafeFrame should use randomized subdomains for Reservation creatives.


allowOverlayExpansion

  • allowOverlayExpansion: boolean
  • Whether SafeFrame should allow ad content to expand by overlaying page content.


allowPushExpansion

  • allowPushExpansion: boolean
  • Whether SafeFrame should allow ad content to expand by pushing page content.


sandbox

  • sandbox: boolean
  • Whether SafeFrame should use the HTML5 sandbox attribute to prevent top level navigation without user interaction. The only valid value is true (cannot be forced to false). Note that the sandbox attribute disables plugins (e.g. Flash).


useUniqueDomain

  • useUniqueDomain: null | boolean
  • Whether SafeFrame should use randomized subdomains for Reservation creatives. Pass in null to clear the stored value.

  • Note: this feature is enabled by default. See the Use unique SafeFrame domains article for more information.


googletag.Service

Base service class that contains methods common for all services.

Method Summary
addEventListener
Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page.
getSlots
Get the list of slots associated with this service.
removeEventListener
Removes a previously registered listener.


addEventListener

  • addEventListener(eventType: string, listener: (arg: null | object) => void): Service
  • Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page. The following events are supported:

  • An object of the appropriate event type is passed to the listener when it is called.

  • Example
    // 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.pubads().addEventListener('slotOnload', function(event) {
      if (event.slot === targetSlot) {
        // Slot specific logic.
      }
    });
  • Parameters
    eventType: string
    A string representing the type of event generated by GPT. Event types are case sensitive.
    listener: (arg: null | object) => void
    Function that takes a single event object argument.
  • Returns
    Service
    The service object on which the method was called.


getSlots

  • getSlots(): Slot[]
  • Get the list of slots associated with this service.

  • Returns
    Slot[]
    Slots in the order in which they were added to the service.


removeEventListener

  • removeEventListener(eventType: string, listener: (arg: null | object) => void): boolean
  • Removes a previously registered listener.

  • Example
    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();
    });
  • Parameters
    eventType: string
    A string representing the type of event generated by GPT. Event types are case sensitive.
    listener: (arg: null | object) => void
    Function that takes a single event object argument.
  • Returns
    boolean
    Whether existing event listener was removed.


googletag.SizeMappingBuilder

Builder for size mapping specification objects. This builder is provided to help easily construct size specifications.

See the Ad sizes guide for more details.

Method Summary
addSize
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.


addSize

  • addSize(viewportSize: SingleSizeArray, slotSize: GeneralSize): SizeMappingBuilder
  • Adds a mapping from a single-size array (representing the viewport) to a single- or multi-size array representing the slot.

  • Example
    var mapping1 =
        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();
    
    var mapping2 =
        googletag.sizeMapping()
                 .addSize([1024, 768], [970, 250])
                 .addSize([980, 690], [])
                 .addSize([640, 480], [120, 60])
                 .addSize([0, 0], [])
                 .build();
    
    // mapping2 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
  • Builds a size map specification from the mappings added to this builder.

    If any invalid mappings have been supplied, this method will return null. Otherwise it returns a specification in the correct format to pass to googletag.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

Slot is an object representing a single ad slot on a page.

Method Summary
addService
Adds a Service to this slot.
clearCategoryExclusions
Clears all slot-level ad category exclusion labels for this slot.
clearTargeting
Clears specific or all custom slot-level targeting parameters for this slot.
defineSizeMapping
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.
getAdUnitPath
Returns the full path of the ad unit, with the network code and ad unit path.
getAttributeKeys
Returns the list of attribute keys set on this slot.
getCategoryExclusions
Returns the ad category exclusion labels for this slot.
getResponseInformation
Returns the ad response information.
getSlotElementId
Returns the ID of the slot div provided when the slot was defined.
getTargeting
Returns a specific custom targeting parameter set on this slot.
getTargetingKeys
Returns the list of all custom targeting keys set on this slot.
set
Sets a value for an AdSense attribute on this ad slot.
setCategoryExclusion
Sets a slot-level ad category exclusion label on this slot.
setClickUrl
Sets the click URL to which users will be redirected after clicking on the ad.
setCollapseEmptyDiv
Sets whether the slot div should be hidden when there is no ad in the slot.
setForceSafeFrame
Configures whether ads in this slot should be forced to be rendered using a SafeFrame container.
setSafeFrameConfig
Sets the slot-level preferences for SafeFrame configuration.
setTargeting
Sets a custom targeting parameter for this slot.
updateTargetingFromMap
Sets custom targeting parameters for this slot, from a key:value map in a JSON object.


addService

  • addService(service: Service): Slot
  • Adds a Service to this slot.

  • Example
    googletag.defineSlot('/1234567/sports', [160, 600])
             .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
  • Clears all slot-level ad category exclusion labels for this slot.

  • Example
    // Set category exclusion to exclude ads with 'AirlineAd' labels.
    var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
                        .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
  • Clears specific or all custom slot-level targeting parameters for this slot.

  • Example
    var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
                        .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.
  • Parameters
    key?: string
    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
  • Sets an array of mappings from a minimum viewport size to slot size for this slot.

    See the Ad sizes guide for more details.

  • Example
    var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
                        .addService(googletag.pubads());
    
    var mapping = googletag.sizeMapping()
                           .addSize([100, 100], [88, 31])
                           .addSize([320, 400], [[320, 50], [300, 50]])
                           .build();
    
    slot.defineSizeMapping(mapping);
  • 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
  • Returns the value for the AdSense attribute associated with the given key for this slot. To see service-level attributes inherited by this slot, use PubAdsService.get().

  • Example
    var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
                        .set('adsense_background_color', '#FFFFFF')
                        .addService(googletag.pubads());
    
    var color = slot.get('adsense_background_color');
    // color == '#FFFFFF'.
  • 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
  • Returns the full path of the ad unit, with the network code and ad unit path.

  • Example
    var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
                        .addService(googletag.pubads());
    
    var path = slot.getAdUnitPath();
    // path is '/1234567/sports'
  • Returns
    string
    Ad unit path.


getAttributeKeys

  • getAttributeKeys(): string[]
  • Returns the list of attribute keys set on this slot. To see the keys of service-level attributes inherited by this slot, use PubAdsService.getAttributeKeys().

  • Example
    var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
                        .set('adsense_background_color', '#FFFFFF')
                        .set('adsense_border_color', '#AABBCC')
                        .addService(googletag.pubads());
    
    var keys = slot.getAttributeKeys();
    // Keys are ['adsense_background_color', 'adsense_border_color'].
  • Returns
    string[]
    Array of attribute keys. Ordering is undefined.


getCategoryExclusions

  • getCategoryExclusions(): string[]
  • Returns the ad category exclusion labels for this slot.

  • Example
    var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
                        .setCategoryExclusion('AirlineAd')
                        .setCategoryExclusion('TrainAd')
                        .addService(googletag.pubads());
    
    var exclusions = slot.getCategoryExclusions();
    // exclusions are ['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
  • Returns the ad response information. This is based on the last ad response for the slot. If this is called when the slot has no ad, null will be returned.

  • Returns
    null | ResponseInformation
    The latest ad response information, or null if the slot has no ad.


getSlotElementId

  • getSlotElementId(): string
  • Returns the ID of the slot div provided when the slot was defined.

  • Example
    var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
                        .addService(googletag.pubads());
    
    var slotElementId = slot.getSlotElementId();
    // slotElementId is 'div-1'
  • Returns
    string
    Slot div ID.


getTargeting

  • getTargeting(key: string): string[]
  • Returns a specific custom targeting parameter set on this slot. Service-level targeting parameters are not included.

  • Example
    var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
                        .setTargeting('allow_expandable', 'true')
                        .addService(googletag.pubads());
    
    var param = slot.getTargeting('allow_expandable');
    // param is ['true']
    
    var param = slot.getTargeting('age');
    // param is [] (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[]
  • Returns the list of all custom targeting keys set on this slot. Service-level targeting keys are not included.

  • Example
    var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
                        .setTargeting('allow_expandable', 'true')
                        .setTargeting('interests', ['sports', 'music'])
                        .addService(googletag.pubads());
    
    var keys = slot.getTargetingKeys();
    // keys are ['interests', 'allow_expandable'].
  • Returns
    string[]
    Array of targeting keys. Ordering is undefined.


set

  • set(key: string, value: string): Slot
  • Sets a value for an AdSense attribute on this ad slot. This will override any values set at the service level for this key.

    See the AdSense Attributes for a list of available keys and values. 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
    // Setting an attribute on a single ad slot.
    googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
             .set('adsense_background_color', '#FFFFFF')
             .addService(googletag.pubads());
  • 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
  • Sets a slot-level ad category exclusion label on this slot.

    See the article on ad exclusion for more details.

  • Example
    // Label = AirlineAd
    googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
             .setCategoryExclusion('AirlineAd')
             .addService(googletag.pubads());
  • 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
  • Sets the click URL to which users will be redirected after clicking on the ad.

    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
    googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
             .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
  • Sets whether the slot div should be hidden when there is no ad in the slot. This overrides the service-level settings.

  • Example
    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.
    collapseBeforeAdFetch?: boolean
    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.


setForceSafeFrame

  • setForceSafeFrame(forceSafeFrame: boolean): Slot
  • Configures whether ads in this slot should be forced to be rendered using a SafeFrame container. For more details, please see the article on rendering creatives using SafeFrame.

    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 (see related article).
    • 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
    googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
             .setForceSafeFrame(true)
             .addService(googletag.pubads());
  • 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
  • Sets the slot-level preferences for SafeFrame configuration. Any unrecognized keys in the config object will be ignored. The entire config will be ignored if an invalid value is passed for a recognized key.

  • These slot-level preferences, if specified, will override any page-level preferences. For more details, please see the article on rendering creatives using SafeFrame.

  • Example
    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();
  • 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
  • Sets a custom targeting parameter for this slot. Calling this method multiple times for the same key will overwrite old values. Values set here will overwrite targeting parameters set at the service-level. These keys are defined in your Google Ad Manager account.

  • Example
    var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1')
                        .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']);
  • 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
  • Sets custom targeting parameters for this slot, from a key:value map in a JSON object. This is the same as calling setTargeting(key,value) for all the key values of the object. These keys are defined in your Google Ad Manager account.

    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
    var slot = googletag.defineSlot('/1234567/sports', [160, 600],
                                    'div-1');
    
    slot.updateTargetingFromMap({
      'color': 'red',
      'interests': ['sports','music','movies']
    });
  • Parameters
    map: {  [adUnitPath: string]: string | string[] }
    Targeting parameter key:value map.
  • Returns
    Slot
    The slot object on which the method was called.


googletag.events.Event

Base Interface for all GPT events. All GPT events below will have the following fields.

Property Summary
serviceName
Name of the service that triggered the event.
slot
The slot that triggered the event.


serviceName

  • serviceName: string
  • Name of the service that triggered the event.


slot

  • slot: Slot
  • The slot that triggered the event.


googletag.events.ImpressionViewableEvent

Extends Event

This event is fired when an impression becomes viewable, according to the Active View criteria.

Property Summary
serviceName
Name of the service that triggered the event.
slot
The slot that triggered the event.
Example
// This listener is called when an impression becomes viewable.
var targetSlot = ...;
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.
      }
    }
);


googletag.events.SlotOnloadEvent

Extends Event

This event is fired when the creative's iframe fires its load event. When rendering rich media ads in sync rendering mode, no iframe is used so no SlotOnloadEvent will be fired.

Property Summary
serviceName
Name of the service that triggered the event.
slot
The slot that triggered the event.
Example
// This listener is called when a creative iframe load event fires.
var targetSlot = ...;
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.
  }
});


googletag.events.SlotRenderEndedEvent

Extends Event

This event is fired when the creative code is injected into a slot. This event will occur before the creative's resources are fetched, so the creative may not be visible yet. If you need to know when all creative resources for a slot have finished loading, consider the SlotOnloadEvent instead.

Property Summary
advertiserId
Advertiser ID of the rendered ad.
campaignId
Campaign ID of the rendered ad.
creativeId
Creative ID of the rendered reservation ad.
isEmpty
Whether an ad was returned for the slot.
lineItemId
Line item ID of the rendered reservation ad.
serviceName
Name of the service that triggered the event.
size
Indicates the pixel size of the rendered creative.
slot
The slot that triggered the event.
sourceAgnosticCreativeId
Creative ID of the rendered reservation or backfill ad.
sourceAgnosticLineItemId
Line item ID of the rendered reservation or backfill ad.
Example
// This listener is called when a slot has finished rendering.
var targetSlot = ...;
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('Creative ID: ', event.creativeId);
      console.log('Is empty?:', event.isEmpty);
      console.log('Line Item ID:', event.lineItemId);
      console.log('Size:', event.size);
      console.log('Source Agnostic Creative ID:',
                  event.sourceAgnosticCreativeId);
      console.log('Source Agnostic Line Item ID:',
                  event.sourceAgnosticLineItemId);
      console.groupEnd();

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


advertiserId

  • advertiserId: null | number
  • Advertiser ID of the rendered ad. Value is null for empty slots, backfill ads, and creatives rendered by services other than PubAdsService.


campaignId

  • campaignId: null | number
  • Campaign ID of the rendered ad. Value is null for empty slots, backfill ads, and creatives rendered by services other than PubAdsService.


creativeId

  • creativeId: null | number
  • Creative ID of the rendered reservation ad. Value is null for empty slots, backfill ads, and creatives rendered by services other than PubAdsService.


isEmpty

  • isEmpty: boolean
  • Whether an ad was returned for the slot. Value is true if no ad was returned, false otherwise.


lineItemId

  • lineItemId: null | number
  • Line item ID of the rendered reservation ad. Value is null for empty slots, backfill ads, and creatives rendered by services other than PubAdsService.


size

  • size: null | string | number[]
  • Indicates the pixel size of the rendered creative. Example: [728, 90]. Value is null for empty ad slots.


sourceAgnosticCreativeId

  • sourceAgnosticCreativeId: null | number
  • Creative ID of the rendered reservation or backfill ad. Value is 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
  • Line item ID of the rendered reservation or backfill ad. Value is null if the ad is not a reservation or line item backfill, or the creative is rendered by services other than PubAdsService.


googletag.events.SlotRequestedEvent

Extends Event

This event is fired when an ad has been requested for a particular slot.

Property Summary
serviceName
Name of the service that triggered the event.
slot
The slot that triggered the event.
Example
// 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.pubads().addEventListener('slotRequested', function(event) {
  var slot = event.slot;
  console.log('Slot', slot.getSlotElementId(), 'has been requested.');

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


googletag.events.SlotResponseReceived

Extends Event

This event is fired when an ad response has been received for a particular slot.

Property Summary
serviceName
Name of the service that triggered the event.
slot
The slot that triggered the event.
Example
// This listener is called when an ad response has been received
// for a slot.
var targetSlot = ...;
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.
      }
    }
);


googletag.events.SlotVisibilityChangedEvent

Extends Event

This event is fired whenever the on-screen percentage of an ad slot's area changes. The event is throttled and will not fire more often than once every 200ms.

Property Summary
inViewPercentage
The percentage of the ad's area that is visible.
serviceName
Name of the service that triggered the event.
slot
The slot that triggered the event.
Example
// This listener is called whenever the on-screen percentage of an
// ad slot's area changes.
var targetSlot = ...;
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:', event.inViewPercentage + '%');
      console.groupEnd();

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


inViewPercentage

  • inViewPercentage: number
  • The percentage of the ad's area that is visible. Value is a number between 0 and 100.