Hide

GPT Reference

Type Definitions

Types
googletag.GeneralSizeArray (googletag.SingleSizeArray|googletag.MultiSizeArray)
googletag.MultiSizeArray Array.<!googletag.SingleSizeArray>
googletag.SingleSizeArray Array.<number>
googletag.SizeMapping Array.<!googletag.GeneralSizeArray>
googletag.SizeMappingArray Array.<!googletag.SizeMapping>

googletag

This is the global namespace that the Google Publisher Tag uses for its API.

Field Summary
googletag.apiReady
Flag indicating that GPT API is loaded and ready to be called.
googletag.cmd
Reference to the global command queue for asynchronous execution of GPT-related calls.
googletag.pubadsReady
Flag indicating that Pubads service is enabled, loaded and fully operational.

Method Summary
googletag.companionAds()
Returns a reference to the companion ads service.
googletag.content()
Returns a reference to the content service.
googletag.defineOutOfPageSlot(adUnitPath, opt_div)
Constructs an out-of-page (interstitial) ad slot with the given ad unit path.
googletag.defineSlot(adUnitPath, size, opt_div)
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.
googletag.disablePublisherConsole()
Disables the Google Publisher Console.
googletag.display(div)
Instructs slot services to render the slot.
googletag.enableServices()
Enables all GPT services that have been defined for ad slots on the page.
googletag.getVersion()
Returns the current version of GPT.
googletag.pubads()
Returns a reference to the pubads service.
googletag.sizeMapping()
Creates a new SizeMappingBuilder.


boolean|undefined googletag.apiReady

Flag indicating that 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>


!Array.<function()>|!googletag.CommandArray googletag.cmd

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


boolean|undefined googletag.pubadsReady

Flag indicating that Pubads service is enabled, loaded and fully operational. This property will be simply undefined until googletag.enableServices() is called and Pubads service is loaded and initialized.


!googletag.CompanionAdsService googletag.companionAds()

Returns a reference to the companion ads service.

Returns
!googletag.CompanionAdsService
Instance of the companion ads service.


!googletag.ContentService googletag.content()

Returns a reference to the content service.

Returns
!googletag.ContentService
Instance of the content service.


googletag.Slot googletag.defineOutOfPageSlot(adUnitPath, opt_div)

Constructs an out-of-page (interstitial) ad slot with the given ad unit path. opt_div is the ID of the div element that will contain the ad.
See the article on out-of-page creatives for Premium for more details.

Parameters
string adUnitPath
Full path of the ad unit with the network code and ad unit name.
string= opt_div
ID of the div that will contain this ad unit.

Returns
googletag.Slot
The newly created slot.

Example:
googletag.defineOutOfPageSlot('/1234567/sports', 'div-1');


googletag.Slot googletag.defineSlot(adUnitPath, size, opt_div)

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.

Parameters
string adUnitPath
Full path of the ad unit with the network code and unit name.
googletag.GeneralSizeArray size
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.
string= opt_div
ID of the div that will contain this ad unit.

Returns
googletag.Slot
The newly created slot.

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


googletag.disablePublisherConsole()

Disables the Google Publisher Console.
See the article on Publisher Console for Small Business or Premium for more details.


googletag.display(div)

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 moment display is called will be fetched in a single instance of googletag.display(). To force an ad slot not to display, the entire div must be removed.

Parameters
string div
ID of the div element containing the ad slot.

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


googletag.enableServices()

Enables all GPT services that have been defined for ad slots on the page.


string googletag.getVersion()

Returns the current version of GPT.

Returns
string
Version string.


!googletag.PubAdsService googletag.pubads()

Returns a reference to the pubads service.

Returns
!googletag.PubAdsService
Instance of the pubads service.


!googletag.SizeMappingBuilder googletag.sizeMapping()

Creates a new SizeMappingBuilder.
See the article on responsive design for Small Business or Premium for more details.

Returns
!googletag.SizeMappingBuilder
A new builder.


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(f)
Executes the sequence of functions specified in the arguments in order.


number push(f)

Executes the sequence of functions specified in the arguments in order.

Parameters
function() f
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).

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

googletag.CompanionAdsService

Extends googletag.Service.

Companion Ads service. This service is used by video ads to show companion ads. See the article for Small Business or Premium for more details.

Method Summary
enableSyncLoading()
Enables the service implementation to be loaded synchronously.
setRefreshUnfilledSlots(value)
Sets whether companion slots that have not been filled will be automatically backfilled.


enableSyncLoading()

Enables the service implementation to be loaded synchronously. This needs to be called before googletag.enableServices().
Note: this call can be only used if gpt.js is also loaded synchronously, for example, by using a script element. If called when GPT is loaded asynchronously, the outcome of the loading is undefined.


setRefreshUnfilledSlots(value)

Sets whether companion slots that have not been filled will be automatically backfilled. Only slots that are also registered with the pubads service will be backfilled. This method can be called multiple times during the page's lifetime to turn backfill on and off.

Parameters
boolean value
true to automatically backfill unfilled slots, false to leave them unchanged.

Example:
googletag.companionAds().setRefreshUnfilledSlots(true);

googletag.ContentService

Extends googletag.Service.

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

Method Summary
setContent(slot, content)
Fills a slot with the given content.


setContent(slot, content)

Fills a slot with the given content. If services are not yet enabled, stores the content and fills it in when services are enabled.

Parameters
!googletag.Slot slot
The slot to be filled.
string content
The HTML content for the slot.

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

googletag.PassbackSlot

Specialized slot similar to googletag.Slot, but only including those properties that are relevant to passback slots. See the article on passbacks for Small Business or Premium for more details.

Method Summary
display()
Initiates rendering of this slot.
setClickUrl(url)
Sets the click URL to which users will be redirected after clicking on the ad.
setTagForChildDirectedTreatment(value)
Configures whether the passback slot should be tagged for child-directed treatment.
setTargeting(key, value)
Sets a custom targeting parameter for this slot.


display()

Initiates rendering of this slot.
Example:
googletag.pubads().definePassback('/1234567/sports', [468, 60]).display();
 


!googletag.PassbackSlot setClickUrl(url)

Sets the click URL to which users will be redirected after clicking on the ad. The DFP servers still record a click even if the click URL is replaced, but any landing page URL associated with the creative that is served is overridden. Subsequent calls overwrite the value.

Parameters
string url
The click URL to set.

Returns
!googletag.PassbackSlot
The slot object on which the method was called.

Example:
googletag.pubads().definePassback('/1234567/sports', [468, 60]).
    setClickUrl('https://www.example.com').
    display();


!googletag.PassbackSlot setTagForChildDirectedTreatment(value)

Configures whether the passback slot should be tagged for child-directed treatment. Although in general TFCD is treated as a page-level setting, passbacks operate in a separate context, so for a passback, this is a slot-level setting.
See the TFCD article for Small Business or Premium for more details.

Parameters
number value
The child-directed treatment tag status to set. See the article for supported values.

Returns
!googletag.PassbackSlot
The slot object on which the method was called.

Example:
googletag.pubads().definePassback('/1234567/sports', [468, 60]).
    setTagForChildDirectedTreatment(1).
    display();


!googletag.PassbackSlot setTargeting(key, value)

Sets a custom targeting parameter for this slot. Calling this multiple times for the same key will overwrite old values. Values set here will overwrite targeting parameters set on the service that this slot uses.

Parameters
string key
Targeting parameter key.
string|!Array.<string> value
Targeting parameter value or list of values.

Returns
!googletag.PassbackSlot
The slot object on which the method was called.

Example:
googletag.pubads().definePassback('/1234567/sports', [468, 60]).
    setTargeting('color', 'red').
    setTargeting('sport', ['rugby', 'rowing']).
    display();

googletag.PubAdsService

Extends googletag.Service.

Publisher Ads service. This service is used to fetch and show ads from your DFP account.

Method Summary
clear(opt_slots)
Removes the ads from the given slots and replaces them with blank content.
clearCategoryExclusions()
Clears all page-level ad category exclusion labels.
clearTagForChildDirectedTreatment()
Clears the configuration for whether the page should be treated as child-directed.
clearTargeting(key)
Clears custom targeting parameters for a given key.
collapseEmptyDivs(opt_collapseBeforeAdFetch)
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.
definePassback(adUnitPath, size)
Constructs a passback slot.
disableInitialLoad()
Disables requests for ads on page load, but allows ads to be requested with a googletag.pubads().refresh() call.
display(adUnitPath, size, opt_div, opt_clickUrl)
Constructs and displays an ad slot with the given ad unit path and size.
enableAsyncRendering()
Enables async rendering mode to enable non-blocking fetching and rendering of ads.
enableSingleRequest()
Enables single request mode for fetching multiple ads at the same time.
enableSyncRendering()
Enables sync rendering mode to enable blocking fetching and rendering of ads.
enableVideoAds()
Signals to GPT that video ads will be present on the page.
get(key)
Returns the value for the AdSense attribute associated with the given key.
getAttributeKeys()
Returns the attribute keys that have been set on this service.
refresh(opt_slots, opt_options)
Fetches and displays new ads for specific or all slots on the page.
set(key, value)
Sets values for AdSense attributes that apply to all ad slots under the publisher ads service.
setCategoryExclusion(categoryExclusion)
Sets a page-level ad category exclusion for the given label name.
setCentering(centerAds)
Enables/disables centering of ads.
setCookieOptions(options)
Sets cookie options for GPT on the page.
setLocation(latitudeOrAddress, opt_longitude, opt_radius)
Passes location information from websites so you can geo-target line items to specific locations.
setPublisherProvidedId(ppid)
Sets the value for the publisher-provided ID.
setTagForChildDirectedTreatment(value)
Configures whether the page should be treated as child-directed.
setTargeting(key, value)
Sets custom targeting parameters for a given key that apply to all pubads service ad slots.
setVideoContent(videoContentId, videoCmsId)
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.


boolean clear(opt_slots)

Removes the ads from the given slots and replaces them with blank content.

Parameters
Array.<!googletag.Slot>= opt_slots
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.

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


!googletag.PubAdsService clearCategoryExclusions()

Clears all page-level ad category exclusion labels. This is useful if you want to refresh the slot.

Returns
!googletag.PubAdsService
The service object on which the method was called.

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.


!googletag.PubAdsService clearTagForChildDirectedTreatment()

Clears the configuration for whether the page should be treated as child-directed.
See the TFCD article for Small Business or Premium for more details.

Returns
!googletag.PubAdsService
The service object on which the method was called.

Example:
// Mark ad requests as child-directed.
googletag.pubads().setTagForChildDirectedTreatment(1);

// Clear child-directed setting and return to initial not-set value.
googletag.pubads().clearTagForChildDirectedTreatment();


!googletag.PubAdsService clearTargeting(key)

Clears custom targeting parameters for a given key.

Parameters
string key
Targeting parameter key.

Returns
!googletag.PubAdsService
The service object on which the method was called.

Example:
googletag.pubads().setTargeting('interests', 'sports');
googletag.pubads().setTargeting('colors', 'blue');

googletag.pubads().clearTargeting('interests');
// Targetting 'colors' is still present, while 'interests' was cleared.


boolean collapseEmptyDivs(opt_collapseBeforeAdFetch)

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 article on collapsing empty divs for Small Business or Premium for more details.

Parameters
boolean= opt_collapseBeforeAdFetch
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.


googletag.PassbackSlot definePassback(adUnitPath, size)

Constructs a passback slot. A passback is where a GPT snippet is used as a creative in an ad serving system. The ad serving system could be DFP or a third party. In this case, the ads are always requested synchronously in non-single request mode.
See the article on passbacks for Small Business or Premium for more details.

Parameters
string adUnitPath
The ad unit path of the slot to use as a passback.
!googletag.GeneralSizeArray size
The size of the slot.

Returns
googletag.PassbackSlot
The new passback object or null if the method was called with invalid arguments.

Example:
<script src="//www.googletagservices.com/tag/js/gpt.js">
  googletag.pubads().definePassback('/1234567/sports', [468, 60]).display();
</script>


disableInitialLoad()

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(adUnitPath, size, opt_div, opt_clickUrl)

Constructs and displays an ad slot with the given ad unit path and size. This method does not work with single request mode.

Parameters
string adUnitPath
Ad unit path of slot to be rendered.
!googletag.GeneralSizeArray size
Width and height of the slot.
string= opt_div
ID of the div containing the slot.
string= opt_clickUrl
The click URL to use on this slot.

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


boolean enableAsyncRendering()

Enables async rendering mode to enable non-blocking fetching and rendering of ads. Because the service uses asynchronous rendering by default, you only need to use this method to override a previous setting. Async mode must be set before the service is enabled.

Returns
boolean
Returns true if async rendering mode was enabled and false if it is impossible to enable async rendering mode because the method was called after the service was enabled.


boolean enableSingleRequest()

Enables single request mode for fetching multiple ads at the same time. This requires all pubads slots to be defined and added to the pubads service 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.


boolean enableSyncRendering()

Enables sync rendering mode to enable blocking fetching and rendering of ads. This mode must be set before the service is enabled. Synchronous rendering also requires that the GPT JavaScript be loaded synchronously.

Returns
boolean
Returns true if sync rendering mode was enabled and false if it is impossible to enable sync rendering mode because the method was called after the service was enabled.


enableVideoAds()

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.


?string get(key)

Returns the value for the AdSense attribute associated with the given key.

Parameters
string key
Name of the attribute to look for.

Returns
?string
Current value for the attribute key, or null if the key is not present.

Example:
googletag.pubads().set('adsense_background_color', '#FFFFFF');
var color = googletag.pubads().get('adsense_background_color');
// color == '#FFFFFF'.


!Array.<string> getAttributeKeys()

Returns the attribute keys that have been set on this service.

Returns
!Array.<string>
Array of attribute keys set on this service. Ordering is undefined.

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


refresh(opt_slots, opt_options)

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.

Parameters
Array.<!googletag.Slot>= opt_slots
The slots to refresh. Array is optional; all slots will be refreshed if it is unspecified.
{changeCorrelator: boolean}= opt_options
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.

Example:
// The calls to construct slots 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 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});


!googletag.PubAdsService set(key, value)

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 the first display call.

Parameters
string key
The name of the attribute.
string value
Attribute value.

Returns
!googletag.PubAdsService
The service object on which the method was called.

Example:
googletag.pubads().set('adsense_background_color', '#FFFFFF');


!googletag.PubAdsService setCategoryExclusion(categoryExclusion)

Sets a page-level ad category exclusion for the given label name.
See the article on ad exclusion for Small Business or Premium for more details.

Parameters
string categoryExclusion
The ad category exclusion label to add.

Returns
!googletag.PubAdsService
The service object on which the method was called.

Example:
// Label = AirlineAd.
googletag.pubads().setCategoryExclusion('AirlineAd');


setCentering(centerAds)

Enables/disables centering of ads. This mode must be set before the service is enabled. Centering is disabled by default. In legacy gpt_mobile.js, centering is enabled by default.

Parameters
boolean centerAds
true to center ads, false to left-align them.

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


!googletag.PubAdsService setCookieOptions(options)

Sets cookie options for GPT on the page.
See the article about cookie options for Small Business or Premium for more details.

Parameters
number options
The cookie options to set. See the article for supported values.

Returns
!googletag.PubAdsService
The service object on which the method was called.

Example:
googletag.pubads().setCookieOptions(1);


!googletag.PubAdsService setLocation(latitudeOrAddress, opt_longitude, opt_radius)

Passes location information from websites so you can geo-target line items to specific locations. DFP will not use location data unless this feature has been enabled for your network. To enable this feature, please contact your account manager.

Parameters
string|number latitudeOrAddress
Latitude or freeform address.
number= opt_longitude
The longitude (if a latitude was provided as first argument).
number= opt_radius
The radius in millimeters. Will be rounded to closest integer. Only used when passing the latitude and longitude.

Returns
!googletag.PubAdsService
The service object on which the method was called.

Example:
// Latitude, longitude:
googletag.pubads().setLocation(34, -45.12);

// Latitude, longitude, and precision in millimeters:
googletag.pubads().setLocation(34, -45.12, 10000);

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


!googletag.PubAdsService setPublisherProvidedId(ppid)

Sets the value for the publisher-provided ID. See the article on PPID for Premium for more details.

Parameters
string ppid
An alphanumeric ID provided by the publisher with a recommended maximum of 150 characters.

Returns
!googletag.PubAdsService
The service object on which the method was called.

Example:
googletag.pubads().setPublisherProvidedId('AB123456789');


!googletag.PubAdsService setTagForChildDirectedTreatment(value)

Configures whether the page should be treated as child-directed.
See the TFCD article for Small Business or Premium for more details.

Parameters
number value
The child-directed treatment tag status to set. See the article for supported values.

Returns
!googletag.PubAdsService
The service object on which the method was called.

Example:
// Mark ad requests as child-directed.
googletag.pubads().setTagForChildDirectedTreatment(1);


!googletag.PubAdsService setTargeting(key, value)

Sets custom targeting parameters for a given key that apply to all pubads service ad slots. Calling this multiple times for the same key will overwrite old values. These keys are defined in your DFP account.

Parameters
string key
Targeting parameter key.
string|!Array.<string> value
Targeting parameter value or array of values.

Returns
!googletag.PubAdsService
The service object on which the method was called.

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','movies']);


setVideoContent(videoContentId, videoCmsId)

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 DFP content ingestion service.
See the article on video content for Premium for more details.

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


!googletag.PubAdsService updateCorrelator()

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.

Returns
!googletag.PubAdsService
The service object on which the function was called.

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.

googletag.Service

Base service class that contains methods common for all services.

Method Summary
addEventListener(eventType, listener)
Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page.


!googletag.Service addEventListener(eventType, listener)

Registers a listener that allows you to set up and call a JavaScript function when a specific GPT event happens on the page. Currently, only the 'slotRenderEnded' event is supported.
Slot render ended event. This event is fired when a slot on the page has finished rendering. The event is fired only for the service which rendered the slot. The event object passed to the listener function is an instance of googletag.events.SlotRenderEndedEvent.

Parameters
string eventType
A string representing the type of event generated by GPT. Event types are case sensitive.
function(Object) listener
Function that takes a single event object argument.

Returns
!googletag.Service
The service object on which the method was called.

Example:
// Slot render ended listener. The listener will be called only when
// the pubads service renders a slot. To listen to companion ads, add
// a similar listener to googletag.companionAds().
googletag.pubads().addEventListener('slotRenderEnded', function(event) {
  console.log('Slot has been rendered:');
  console.log(event);
});

// Listeners operate at service level, which means that you cannot add a
// listener for a slotRenderEnded 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('slotRenderEnded', function(event) {
  if (event.slot === targetSlot) {
    // Slot specific logic
  }
});

googletag.SizeMappingBuilder

Builder for size mapping specification objects. This builder is provided to help easily construct size specifications.
See the article on responsive design for Small Business or Premium for more details.

Method Summary
addSize(viewportSize, slotSize)
Adds a mapping from a single-size array representing the viewport to either a single-size array or a multi-size array representing the slot.
build()
Builds a size map specification from the mappings added to this builder.


!googletag.SizeMappingBuilder addSize(viewportSize, slotSize)

Adds a mapping from a single-size array representing the viewport to either a single-size array or a multi-size array representing the slot.

Parameters
!googletag.SingleSizeArray viewportSize
The size of the viewport for this mapping entry.
!googletag.GeneralSizeArray slotSize
The sizes of the slot for this mapping entry.

Returns
!googletag.SizeMappingBuilder
A reference to this builder.

Example:
var mapping1 = googletag.sizeMapping().
    addSize([1024, 768], [970, 250]).
    addSize([980, 690], [728, 90]).
    addSize([640, 480], [120, 60]).
    addSize([0, 0], [88, 31]). // Fits browsers of any size smaller than 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]


googletag.SizeMappingArray build()

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(). The behavior of the builder after calling build() is undefined.

Returns
googletag.SizeMappingArray
The result built by this builder. Can be null if invalid size mappings were supplied.


googletag.Slot

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

Method Summary
addService(service)
Adds a service to this slot.
clearCategoryExclusions()
Clears all slot-level ad category exclusion labels for this slot.
clearTargeting()
Clears all custom slot-level targeting parameters for this slot.
defineSizeMapping(sizeMapping)
Sets an array of mappings from a minimum viewport size to slot size for this slot.
get(key)
Returns the value for the AdSense attribute associated with the given key.
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.
getSlotElementId()
Returns the id of the slot element provided when the slot was defined.
getTargeting(key)
Returns a specific custom targeting parameter set on this slot.
getTargetingKeys()
Returns the list of all custom targeting keys set on this slot.
set(key, value)
Sets a value for an AdSense attribute on a particular ad slot.
setCategoryExclusion(categoryExclusion)
Sets a slot-level ad category exclusion label on this slot.
setClickUrl(value)
Sets the click URL to which users will be redirected after clicking on the ad.
setCollapseEmptyDiv(collapse, opt_collapseBeforeAdFetch)
Sets whether the slot div should be hidden when there is no ad in the slot.
setTargeting(key, value)
Sets a custom targeting parameter for this slot.


!googletag.Slot addService(service)

Adds a service to this slot.

Parameters
!googletag.Service service
The service to be added.

Returns
!googletag.Slot
The slot object on which the method was called.

Example:
googletag.defineSlot('/1234567/sports', [160, 600]).
    addService(googletag.pubads());


!googletag.Slot clearCategoryExclusions()

Clears all slot-level ad category exclusion labels for this slot.

Returns
!googletag.Slot
The slot object on which the method was called.

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.


!googletag.Slot clearTargeting()

Clears all custom slot-level targeting parameters for this slot.

Returns
!googletag.Slot
The slot object on which the method was called.

Example:
var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1').
    setTargeting('allow_expandable', 'true').
    addService(googletag.pubads());

slot.clearTargeting();


!googletag.Slot defineSizeMapping(sizeMapping)

Sets an array of mappings from a minimum viewport size to slot size for this slot.
See the article on responsive design for Small Business or Premium for more details.

Parameters
!googletag.SizeMappingArray sizeMapping
Array of size mappings. You can use googletag.SizeMappingBuilder to create it. Each size mapping is an array of two elements: googletag.SingleSizeArray and googletag.GeneralSizeArray.

Returns
!googletag.Slot
The slot object on which the method was called.

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


?string get(key)

Returns the value for the AdSense attribute associated with the given key. Note that if you intend to see service-level attributes inherited by this slot, you have to use the googletag.PubAdsService.get(key) API.

Parameters
string key
Name of the attribute to look for.

Returns
?string
Current value for the attribute key, or null if the key is not present.

Example:
var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1').
    set('adsense_background_color', '#FFFFFF').
    addService(googletag.pubads());

var color = googletag.pubads().get('adsense_background_color');
// color == '#FFFFFF'.


string getAdUnitPath()

Returns the full path of the ad unit, with the network code and ad unit path.

Returns
string
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'


!Array.<string> getAttributeKeys()

Returns the list of attribute keys set on this slot. If you intend to see the keys of service-level attributes inherited by this slot, you have to use the googletag.PubAdsService.getAttributeKeys() API.

Returns
!Array.<string>
Array of attribute keys. Ordering is undefined.

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 = googletag.pubads().getAttributeKeys();
// Keys are ['adsense_background_color', 'adsense_border_color'].


!Array.<string> getCategoryExclusions()

Returns the ad category exclusion labels for this slot.

Returns
!Array.<string>
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']


string getSlotElementId()

Returns the id of the slot element provided when the slot was defined.

Returns
string
Slot element id.

Example:
var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1').
    addService(googletag.pubads());

var slotElementId = slot.getSlotElementId();
// slotElementId is 'div-1'


!Array.<string> getTargeting(key)

Returns a specific custom targeting parameter set on this slot. Service-level targeting parameters are not included.

Parameters
string key
The targeting key to look for.

Returns
!Array.<string>
The values associated with this key, or an empty array if there is no such key.

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.getTargetting('age');
// param is [] (empty array)


!Array.<string> getTargetingKeys()

Returns the list of all custom targeting keys set on this slot. Service-level targeting keys are not included.

Returns
!Array.<string>
Array of targeting keys. Ordering is undefined.

Example:
var slot = googletag.defineSlot('/1234567/sports', [160, 600], 'div-1').
    setTargeting('allow_expandable', 'true').
    setTargeting('interests', ['sports','music','movies']).
    addService(googletag.pubads());

var keys = slot.getTargetingKeys();
// keys are ['interests', 'allow_expandable'].


!googletag.Slot set(key, value)

Sets a value for an AdSense attribute on a particular 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 any display call.

Parameters
string key
The name of the attribute.
string value
Attribute value.

Returns
!googletag.Slot
The slot object on which the method was called.

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


!googletag.Slot setCategoryExclusion(categoryExclusion)

Sets a slot-level ad category exclusion label on this slot.
See the article on ad exclusion for Small Business or Premium for more details.

Parameters
string categoryExclusion
The ad category exclusion label to add.

Returns
!googletag.Slot
The slot object on which the method was called.

Example:
// Label = AirlineAd
googletag.defineSlot('/1234567/sports', [160, 600], 'div-1').
    setCategoryExclusion('AirlineAd').
    addService(googletag.pubads());


!googletag.Slot setClickUrl(value)

Sets the click URL to which users will be redirected after clicking on the ad. The DFP servers still record a click even if the click URL is replaced, but any landing page URL associated with the creative that is served is overridden. Subsequent calls overwrite the value.

Parameters
string value
The click URL to set.

Returns
!googletag.Slot
The slot object on which the method was called.

Example:
googletag.defineSlot('/1234567/sports', [160, 600], 'div-1').
    setClickUrl('http://www.example.com').
    addService(googletag.pubads());


!googletag.Slot setCollapseEmptyDiv(collapse, opt_collapseBeforeAdFetch)

Sets whether the slot div should be hidden when there is no ad in the slot. This overrides the service-level settings.

Parameters
boolean collapse
Whether to collapse the slot if no ad is returned.
boolean= opt_collapseBeforeAdFetch
Whether to collapse the slot even before an ad is fetched. Ignored if collapse is not true.

Returns
!googletag.Slot
The slot object on which the method was called.

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.


!googletag.Slot setTargeting(key, value)

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 on service level. These keys are defined in your DFP account.

Parameters
string key
Targeting parameter key.
string|!Array.<string> value
Targeting parameter value or array of values.

Returns
!googletag.Slot
The slot object on which the method was called.

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','movies']);

googletag.events.SlotRenderEndedEvent

This event is fired when a slot on the page has finished rendering. The event is fired by the service that rendered the slot. Example: To listen to companion ads, add a listener to the companionAds service, not the pubads service.

Field Summary
creativeId
Creative ID of the rendered ad.
isEmpty
true if no ad was returned for the slot, false otherwise.
lineItemId
Line item ID of the rendered ad.
serviceName
Name of the service that rendered the slot.
size
Indicates the pixel size of the rendered creative.
slot
The slot in which the creative was rendered.


?number creativeId

Creative ID of the rendered ad. Value is null for empty slots, backfill ads or creatives rendered by services other than pubads service.


boolean isEmpty

true if no ad was returned for the slot, false otherwise.


?number lineItemId

Line item ID of the rendered ad. Value is null for empty slots, backfill ads or creatives rendered by services other than pubads service.


string serviceName

Name of the service that rendered the slot.


Array.<number> size

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


!googletag.Slot slot

The slot in which the creative was rendered.

Send feedback about...

Google Publisher Tag