Google Publisher Tag API reference guide

This article provides method summaries and method details for the Google Publisher Tag API.

Method summary

The following method summaries are provided below: googletag, pubService, companionAdsService, contentService, adSlot, googletag.cmd.

Class: googletag

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

  • cmd
    Reference to the global command queue for asynchronous execution of GPT-related calls.

  • .clearCategoryExclusions
    Clears slot-level ad exclusions for a particular ad slot.

  • companionAds()
    Returns a reference to the companion ads service.

  • content()
    Returns a reference to the content service.

  • defineOutOfPageSlot(unitName, divId)
    Constructs an out of page (interstitial) ad slot with the given ad unit name. divId is the ID of the div element that will contain the ad.

  • definePassback (unitName, size)
    When called in a DFP ad tag given to a third-party ad server, passes the tag back to DFP when no matching ad is available on the third-party ad server.

  • defineSlot(unitName, size, divId)
    Constructs an ad slot with the given ad unit name and size. divId is the ID of the div element that will contain this ad slot.

  • display(divId)
    Indicates where on the page the ad slot contents should be displayed.

  • enableServices()
    Enables all Google Publisher Tag services that have been associated with ad slots on the page.

  • pubads()
    Returns a reference to the publisher ads service.

  • setCategoryExclusion()
    Sets an ad category exclusion for the specified label.

  • setLocation()
    Passes precise location information from websites and mobile applications so you can geo-target line items to specific locations.

Class: pubService

API for configuring the DFP publisher ads service. The publisher ads service is the main service used to request ads from Google.

  • addEventListener(eventType, listener)
    This method registers a listener which allows you to set up and call a JavaScript function when a specific GPT event happens on the page.

  • collapseEmptyDivs()
    Constructs an ad slot with the specified parameters and associates it with the publisher service. Equivalent to defineSlot() followed by addService(pubads). Note that using this method does not allow you to use single request mode.

  • enableAsyncRendering()
    Instructs the service to fetch ads asynchronously using iframes in the publisher's domain.

  • enableSingleRequest()
    Requests all ad slot contents in a single request.

  • enableSyncRendering()
    Instructs the service to wait for each ad request to complete before continuing with rendering the page.

  • enableVideoAds()
    Signals to GPT that video ads will be present on the page.

  • noFetch()
    Processes the JavaScript but does not make any HTTP calls for ad slot contents.

  • refresh(slots)
    (Async mode only) Refreshes the specified array of slots on the page with new ads.

  • set(key, value)
    Sets values for AdSense parameters that apply to all pubService ad slots.

  • setTagForChildDirectedTreatment(options)
    Sets the child-directed status of the ad request.

  • setTargeting(key, value)
    Sets values for targeting keys that apply to all pubService ad slots.

  • setVideoContent(videoContentId, videoCmsId)
    Sets the video content information to be sent along with the ad requests for targeting and content exclusion purposes.

Class: companionAdsService

API for configuring the DFP companion ads service.

  • enableSyncLoading()
    Enables the service implementation to be loaded synchronously.

  • setRefreshUnfilledSlots(value)
    Enables or disables the automatic refresh of companion slots that have not been filled.

Class: contentService

API for configuring the DFP content service. The content service gives you control over an ad slot to display other ads before a companion ad is requested.

  • setContent(slot, content)
    Fills a slot with the given contents. If the slot is not yet rendered (or does not have an associated div), the contents are stored and the slot is filled when the div is created.

Class: adSlot

API for configuring a specific ad slot on the page.

  • addService(service)
    Adds the ad slot to the specified Google tag service.

  • clearTargeting()
    Clears all slot-level targeting for a particular ad slot.

  • set(key, value)
    Sets values for AdSense parameters on a particular ad slot.

  • setClickUrl(url)
    Sets the redirect URL for a click on an ad in a particular slot. The DoubleClick 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.

  • setCollapseEmptyDiv(collapse, collapseBeforeAdFetch [optional])
    Specifies a slot-specific override to the page-wide div collapse behavior that was specified through pubService.collapseEmptyDivs().

  • setTargeting(key, value)
    Sets values for targeting keys on a particular ad slot.

Class: googletag.cmd

API for queueing GPT function calls for execution when ready.

  • push(JsFunction)
    JsFunction will be queued for execution pending the loading of gpt.js.

 

Method details

Method details for googletag

companionAds

googletag.companionAds()

Returns a reference to the companion ads service.

  • Returns:

    • companionAdsService: A reference to the companion ads service.

content

googletag.content()

Returns a reference to the content service.

  • Returns:

    • contentService: A reference to the content service.

clearCategoryExclusions

.clearCategoryExclusions()

Clears all slot-level ad exclusions for a particular ad slot. This is useful if you want to refresh the slot.

content

googletag.content()

Returns a reference to the content service.

  • Returns:

    • contentService: A reference to the content service.

defineOutOfPageSlot

googletag.defineOutOfPageSlot(unitName, divId)

Constructs an out of page (interstitial) ad slot with the given ad unit name. divId is the ID of the div element that will contain the ad.

  • Parameters:

    • string unitName: Full path of the ad unit with the network code and unit name.

    • string divId: Publisher-specified ID for the div element containing the ad.

  • Returns:

    • adSlot: The newly created ad slot.

  • Example:

    // Ad unit = "/networkCode/unitName"
    googletag.defineOutOfPageSlot("1234567/outofpage", "div-gpt-ad-1");

definePassback

googletag.pubads().definePassback(unitName, size)

When called in a DFP ad tag given to a third-party ad server, passes the tag back to DFP when no matching ad is available on the third-party ad server.

  • Parameters:

    • string unitName: Full path of the ad unit with the network code and unit name.

    • number size: Width and height of the ad unit within brackets and separated by a comma.

  • Returns:

    • passbackSlot: The newly created passback ad slot.

defineSlot

googletag.defineSlot(unitName, size, divId)

Constructs an ad slot with a given ad unit name and size and associates it with the ID of a div element on the page that will contain the ad.

  • Parameters:

    • string unitName: Full path of the ad unit with the network code and unit name.

    • number size: Width and height of the ad unit within brackets and separated by a comma.

    • string divId: Publisher-specified ID for the div element containing the ad.

  • Returns:

    • adSlot: The newly created ad slot.
  • Example:

    // Ad unit = "/networkCode/unitName"; size = [width, height]
    googletag.defineSlot("/1234567/leaderboard", [728, 90], "div-1");

disablePublisherConsole

googletag.disablePublisherConsole()

Disables the Google Publisher Console.

display

googletag.display(divId)

Indicates where on the page the ad slot contents should be displayed. 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 appear in a script block within the div element named in the function call (this restriction is required to seamlessly support the synchronous ad rendering mode).

Note that if single request architecture (SRA) is being used, all ad slots will be called in a single instance of googletag.display(). To force an ad slot not to display, the entire div must be removed.

  • Parameters:

    • string divId: ID of the div element containing the ad slot.

  • Example:

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

enableServices

googletag.enableServices()

Enables all Google Publisher Tag services that have been defined for ad slots on the page. This is only needed once per page but including it multiple times will not cause any harm.

pubads

googletag.pubads()

Returns a reference to the publisher ads service.

  • Returns:

    • pubService: A reference to the publisher ads service.

setCategoryExclusion

googletag.pubads().setCategoryExclusion('labelName');

Sets an ad category exclusion for the given label name. You can set both page-level and slot-level exclusions. (Learn more about setting up ad exclusions)

  • Parameters:

    • labelName: The name of the label that is associated with the line items you want to exclude.

  • Examples:

    Page-level example:

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

    Slot-level example:
    googletag.defineSlot('/networkCode/firstLevelAdUnit/secondLevelAdUnit', [width, height], 'div-gpt-ad-divID')
        .setCategoryExclusion('labelName')
        .addService(googletag.pubads());

setLocation

googletag.pubads().setLocation(latitude, longitude, precision);

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

  • Parameters:

    • latitude: The latitude of the location.
    • longitude: The longitude of the location.
    • precision: The preciseness of the location, in mm.
    • postal code: The 5-digit postal code (US only).
  • Examples:

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

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

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

 

Method details for pubService

addEventListener

pubService.addEventListener(eventType, listener)

Registers a listener which allows you to set up and call a JavaScript function when a specific GPT event happens on the page.

  • Parameters:

    • string eventType: A string representing the type of event generated by GPT. Currently, only the 'slotRenderEnded' event is supported. Event types are case sensitive.

    • function listener: Function that takes a single event object argument. Event objects differ for different events.

  • Returns:

    • this: The service itself. Calls may be chained like:

      service.addEventListener(...).addEventListener(...)

  • Examples:

    • Slot render ended event

      This event is fired when any slot on the page has finished rendering.

      googletag.pubads().addEventListener('slotRenderEnded', function(event) {
       console.log('Creative with id: ' + event.creativeId +
        ' is rendered to slot of size: ' + event.size[0] + 'x' + event.size[1]);
      });

      Structure of slotRenderEnded event object:

      event.slot: slot object reference

      event.isEmpty: boolean, true if no ad was returned for the slot, false otherwise

      event.size: array, indicates size of rendered creative. Example: [728, 90]. Value is null for empty ad slots.

      event.creativeId: number, ID of rendered creative. Value is null for empty slots, backfill ads or creatives rendered by services other than DFP pubService.

      event.lineItemId: number, line item ID of the rendered ad. Value is null for empty slots, backfill ads or creatives rendered by services other than DFP pubService.

      Listeners operate at page-level, which means that one cannot add a listener for a specific slot only. You can programmatically filter a listener to only respond to a certain ad slot, using this pattern:

      var targetSlot = ...;
      googletag.pubads().addEventListener('slotRenderEnded', function(event) {
       if (event.slot === targetSlot) {
        // Slot specific logic
       }
      });

collapseEmptyDivs

pubService.collapseEmptyDivs()

Collapses empty div elements on a page when there is no ad content to display. This must be called before enableServices() for it to have any effect.

disableInitialLoad

pubService.disableInitialLoad()

(Async mode only) Disables the initial fetch of ads from Google when the page is first loaded. Calls to refresh() can still be used to fetch ads.

display

pubService.display(unitName, size, divId)

Constructs an ad slot with the specified parameters and associates it with the publisher service. Equivalent to defineSlot() followed by addService(pubads). Note that using this method does not allow you to use single request mode.

  • Parameters:
    • string unitName: Full path of the ad slot with the network code and unit name.

    • string size: Width and height of the unit (within brackets, and separated by a comma).

    • string divId: Publisher-specified ID for the div element containing the ad.

  • Example:

    // Ad unit = "/networkCode/unitName"; size = [width, height]

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

enableAsyncRendering

pubService.enableAsyncRendering()

Directs the publisher ads service to use the asynchronous rendering mode. In asynchronous rendering, ad requests are made using iframes in the publisher domain (friendly iframes) and the response is written into another friendly iframe. Since the service uses asynchronous rendering by default, publishers would only need to use this method to override a previous setting. As with most service-level settings, this should be called prior to enabling the service.

enableSingleRequest

pubService.enableSingleRequest()

Directs the publisher ads service to make a single request when fetching content for multiple ad slots. This should be called prior to enabling the service.

enableSyncRendering

pubService.enableSyncRendering()

Directs the publisher ads service to use synchronous rendering mode. In synchronous rendering, both the ad requests and the rendering of the responses are done directly on the publisher's page in a blocking fashion. While this may increase the latency of the page, it makes available certain types of ad creatives that are not iframe-friendly. This should be called prior to enabling the service. Synchronous rendering also requires that the GPT JavaScript be fetched synchronously.

enableVideoAds

pubService.enableVideoAds()

Signals to GPT that video ads will be present on the page. This enables the application of competitive exclusion constraints on display and video ads. If the video content is known, call setVideoContent in order to use content exclusion for display ads.

noFetch

pubService.noFetch()

Processes the JavaScript but does not make any HTTP calls for ad slot contents.

refresh

pubService.refresh(slots)

(Async mode only) Refreshes the specified array of slots on the page with new ads.

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 function can be used to stop display from fetching an ad.

  • Parameters:

    • array slots: Optional array of slots to refresh. If not supplied, all ad slots are refreshed.

  • Example:

    // The calls to construct an ad and display contents
    var slot1 = googletag.pubads().display("/1234567/leaderboard", [728, 90], "div-1");
    var slot2 = googletag.pubads().display("/1234567/skyscraper", [160, 600], "div-2");

    // The call to refresh fetches a new ad for each slot
    googletag.pubads().refresh([slot1, slot2]);

set

pubService.set(key, value)

Sets values for AdSense parameters that apply to all ad slots under the publisher ads service. 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: Key name of the parameter for which to set a value.

    • string value: Value of the key. Values must either be a string or an array of strings.

  • Example:

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

  • Available keys:

    New parameter Legacy parameter Example Allowed values
    adsense_channel_ids

    google_ad_channel

    271828183+314159265

    valid AdSense channel IDs, separated by '+'

    adsense_ad_types

    google_ad_type

    text_image

    text, image, text_image

    adsense_ad_format

    google_ad_format

    250x250_as

    468x60_as, 234x60_as, 125x125_as, 120x600_as, 160x600_as, 180x150_as, 120x240_as, 200x200_as, 250x250_as, 300x250_as, 336x280_as, 728x90_as

    adsense_background_color

    google_color_bg

    #000000

    hexadecimal colors

    adsense_border_color

    google_color_border

    #000000

    hexadecimal colors

    adsense_link_color

    google_color_link

    #000000

    hexadecimal colors

    adsense_text_color

    google_color_text

    #000000

    hexadecimal colors

    adsense_url_color

    google_color_url

    #000000

    hexadecimal colors

    adsense_ui_features

    google_ui_features

    rc:10

    rc:10 for very rounded corners, rc:6 for slightly rounded corners, rc:0 for square corners (default)

These AdSense settings are typically set when creating or editing ad slots in the DFP application. This API allows the publisher to override these server-side settings on a per-request basis.

setTagForChildDirectedTreatment

pubService.setTagForChildDirectedTreatment(int options)

Sets the value to mark the ad request as child-directed, or not child-directed.

  • Parameters:

    • int options:

setTargeting

pubService.setTargeting(key, value)

Sets values for targeting keys that apply to all pubService ad slots. These keys are defined by an administrator in the DFP application. Calling this function 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: Key name of the parameter for which to set a value.

    • string value: Value of the key. Values must either be a string or an array of strings.

  • Example:

    // example with a single value for a key
    googletag.pubads().setTargeting("interests", "sports");

    // example with multiple values for a key inside of brackets
    googletag.pubads().setTargeting("interests", ["sports","music","movies"]);

setVideoContent

pubService.setVideoContent(videoContentId, videoCmsId)

Sets the video content information to be sent along with the ad requests for targeting and content exclusion purposes. For videoContentId and videoCmsId, use the values that are provided to the DFP content ingestion service.

 

Method details for companionAdsService

enableSyncLoading

companionAdsService.enableSyncLoading(value)

Enables the service implementation to be loaded synchronously. As with most service-level settings, this should be called prior to enabling the service.

setRefreshUnfilledSlots

companionAdsService.setRefreshUnfilledSlots(value)

Enables or disables the automatic refresh of companion slots that have not been filled.

Video companion dynamic allocation doesn't work with GPT tags used in synchronous mode.
  • Parameters:

    • boolean value: If true, enables the automatic refresh of unfilled slots.

  • Example:

    googletag.companionAds().setRefreshUnfilledSlots(true);

 

Method details for contentService

setContent

contentService.setContent(slot, content)

Fills a slot with the given contents. If the slot is not yet rendered (or does not have an associated div element), the contents are stored and the slot is filled when the div is created.

  • Parameters:

    • slot: The slot to be filled.

    • string: The HTML content for the slot.

  • Example:

    var slot = googletag.defineSlot('/1234567/leaderboard', [728, 90], 'div-1');
    var content = '<a href="www.mydestinationsite.com"><img src="www.mysite.com/img.png"></img></a>';
    googletag.content().setContent(slot, content);

 

Method details for adSlot

addService

adSlot.addService(service)

Adds the ad slot to the specified Google tag service.

  • Parameters:

    • pubService service: Reference to the publisher tag service.

  • Returns:

    • adSlot: The ad slot on which the function was called.

  • Example:

    adSlot.addService(googletag.pubads());

clearTargeting

adSlot.clearTargeting()

Clears all slot-level targeting for a particular ad slot.

set

adSlot.set(key, value)

Sets values for AdSense parameters on a particular ad slot. This will override any values set at the service level for this key. See the set table above for a list of available keys and values. Calling this function 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: Key name of the parameter for which to set a value.

    • string value: Value of the key.

  • Example:

    // setting targeting on a single ad slot
    var slot = googletag.defineSlot("/1234567/skyscraper", [160, 600]).addService(googletag.pubads());
    slot.set("adsense_background_color", "#FFFFFF");

setClickUrl

adSlot.setClickUrl(url)

Sets the redirect URL for a click on an ad in a particular slot. The DoubleClick 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.

  • Parameters:

    • string url: The click URL.

  • Example:

    googletag.defineSlot("/1234567/skyscraper", [160, 600])
      .setClickUrl("http://www.example.com")
      .addService(googletag.pubads());

setTargeting

adSlot.setTargeting(key, value)

Sets values for targeting keys and slot parameters on a particular ad slot. This function will override any values set at the service level for this key. These keys are defined by an administrator in the DFP application. Calling this function 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: Key name of the parameter for which to set a value.

    • string value: Value of the key. Values must either be a string or an array of strings.

  • Example:

    var slot=googletag.defineSlot("/1234567/skyscraper", [160, 600]).addService(googletag.pubads());

    // example with a single value for a key
    slot.setTargeting("allow_expandable", "true");

    // example with multiple values for a key inside of brackets
    slot.setTargeting("interests", ["sports","music","movies"]);

 

setCollapseEmptyDiv

adSlot.setCollapseEmptyDiv(collapse, collapseBeforeAdFetch [optional])

Specifies a slot-specific override to the page-wide div collapse behavior that was specified through pubService.collapseEmptyDivs().

  • Parameters:

    • boolean collapse: Instructs GPT to collapse empty divs after determining that no ads are eligible for the slot
    • boolean collapseBeforeAdFetch: Passing true for this optional parameter causes ad slots to be collapsed immediately on page load. The slot div will only expand when ads are fetched for the slot.
  • Example:

    googletag.defineSlot("/1234567/skyscraper", [160, 600])
    .setCollapseEmptyDiv(true, true)
    // The above will cause the div for this slot to be collapsed
    // when the page is loaded, before ads are requested

    googletag.defineSlot("/1234567/skyscraper", [160, 600])
    .setCollapseEmptyDiv(true)
    // The above will cause the div for this slot to be collapsed
    // only after GPT detects no ads are available for the slot

 

Method details for googletag.cmd

push

googletag.cmd.push(aFunction)

The googletag.cmd variable is initialized to an empty JavaScript Array by the publisher as part of the tags, and cmd.push is the standard Array.push function that adds an element to the end of the array. When the main GPT JavaScript is loaded, it looks through the array and executes all the functions in order. The script then replaces cmd with an internal object whose push function is defined to immediately execute the function argument passed to it. This mechanism allows GPT to reduce perceived latency by fetching the initial JavaScript asynchronously while allowing the browser to continue rendering the page. If the initial JS file is fetched synchronously, calling cmd.push with a function definition is equivalent to calling the function directly.

  • Example:

    googletag.cmd.push(function() {
      googletag.defineSlot("/1234567/ca-pub-12345678912/skyscraper", [160, 600]).
           addService(googletag.pubads());
    });