Privacy & Messaging JavaScript API

Introduction

This API provides tools to interact with messages offered by the Privacy & messaging tab. With it, you can:

  • suppress messaging for any given user
  • query the ad blocking status of a user
  • allow a user to revoke consent (if applicable)

You can also use these tools to gather user consent using some industry standard protocols:

In these cases, the consent status is communicated by way of those APIs.

You can deploy this user messaging functionality on your site in a couple of ways:

  1. For most cases, you don't need to re-tag at all - your existing Google Publisher Tag or AdSense tag deploys user messages once the message is published in the relevant product.
  2. If you're using the ad blocking recovery message, you need to add the ad blocking tag to your page explicitly. See Ad Manager and AdSense tagging instructions for more information.

googlefc is the global namespace that the user messaging functionality uses for its API on the JavaScript Window.

Field Summaries

Name Type Definition
googlefc.controlledMessagingFunction function(!Object) A function that determines whether to proceed with any messaging. This functionality is supported for all message types.
googlefc.callbackQueue !Array<!Object<string, function()>> | !Array<function()> | !googlefc.CallbackQueue Reference to the callback queue for asynchronous execution of user messaging queries.
googlefc.CallbackQueue !Object The type of the callback queue object.
googlefc.AdBlockerStatusEnum !Object<string, number> An enum to represent the user's ad blocker state.
googlefc.AllowAdsStatusEnum !Object<string, number> An enum to represent the user's allow-ads state.
googlefc.ccpa.InitialCcpaStatusEnum !Object<string, number> An enum to represent the user initial CPRA status.
googlefc.ccpa.overrideDnsLink undefined|boolean A boolean which can be set to true to use a custom Do Not Sell link.

Method Summaries

Name Return type Definition
googlefc.showRevocationMessage() undefined Clears the consent record and reloads the googlefc script to show the consent message applicable to the user.
googlefc.getAdBlockerStatus() number Returns a value in the AdBlockerStatusEnum depending on the ad blocking status of the user.
googlefc.getAllowAdsStatus() number Returns a value in the AllowAdsStatusEnum depending on the allow-ads status of the user.
googlefc.ccpa.getInitialCcpaStatus() number Returns a value in the InitialCcpaStatusEnum depending on the initial CPRA status of the user.
googlefc.ccpa.openConfirmationDialog(function(boolean)) undefined Opens the CPRA confirmation dialog if the default Do Not Sell link is overridden.

Testing and debugging on your site

Privacy & messaging provides debugging and testing functionality that lets you see what specific messages (or combinations of messages) look like on your actual site.

Prerequisites:

  • The message(s) you want to preview must be published under the site you're testing against

You can see a live preview on your site by using the following debugging URL parameters:

Debug parameter Allowed values
fc alwaysshow (to trigger debug/preview mode)
fctype ab (Ad blocking messages), ccpa (CPRA opt-out messages), gdpr (GDPR consent messages), monetization (Offerwall messages)

Some examples of how to use this to preview on your site (foo.com):

  • Test CPRA messaging -- http://foo.com/?fc=alwaysshow&fctype=ccpa
  • Test GDPR messaging -- http://foo.com/?fc=alwaysshow&fctype=gdpr

Fields: explanations and examples

googlefc.controlledMessagingFunction {function(!Object)}

A function that determines whether or not messages should display. It can be used to gate message rendering on publisher-specified conditions such as subscriber status or page URL.

When you define googlefc.controlledMessagingFunction on the Window prior to other scripts loading, messages don't display until you call message.proceed(boolean). Calling message.proceed(true) allows messaging to proceed as usual, whereas calling message.proceed(false) prevents any messages from showing for the pageview.

Example: assume that you have this script on the page which defines an async function determineIfUserIsSubscriber() that checks if the logged-in user is a subscriber.

<head>
  <script>
    window.isSubscriber = undefined;
    function determineIfUserIsSubscriber() {
      if (isSubscriber !== undefined) {
        return isSubscriber;
      }
      return new Promise(resolve => {
        setTimeout(() => {
          // Change this to true if you want to test what subscribers would see.
          window.isSubscriber = false;
          resolve(window.isSubscriber);
        }, 1000);
      });
    }
  </script>
</head>

This is an example of how you could use the googlefc.controlledMessagingFunction to only show the message to non-subscribers.

<head>
  <script>
    // Define googlefc and the controlled messaging function on the Window.
    window.googlefc = window.googlefc || {};
    googlefc.controlledMessagingFunction = async (message) => {
      // Determine if the user is a subscriber asynchronously.
      const isSubscriber = await determineIfUserIsSubscriber();

      if (isSubscriber) {
        // If the user is a subscriber, don't show any messages.
        message.proceed(false);
      } else {
        // Otherwise, show messages as usual.
        message.proceed(true);
      }
    }
  </script>
</head>

There is also an extension of this feature that allows publishers part of the Offerwall closed beta to specify that only the Offerwall should be suppressed. Other message types are unaffected when this feature is in effect.

Offerwall-specific controlled messaging is achieved by passing an additional parameter to message.proceed(), an Array of type googlefc.MessageTypeEnum.

Example: This is an example of using googlefc.controlledMessagingFunction to only suppress Offerwall serving for subscribers, without suppressing other message types:

<head>
  <script>
    // Define googlefc and the controlled messaging function on the Window.
    window.googlefc = window.googlefc || {};
    googlefc.controlledMessagingFunction = async (message) => {
     // Determine if the Offerwall should display or not.
     const shouldDisplayOfferwall = await determineIfUserIsSubscriber();
     const applicableMessageTypes = [];

     if (!shouldDisplayOfferwall) {
       // Do not show the Offerwall, but allow other message types to display.
       applicableMessageTypes.push(window.googlefc.MessageTypeEnum.OFFERWALL);
       message.proceed(false, applicableMessageTypes);
     } else {
       // Otherwise, show messages as usual.
       message.proceed(true);
     }
    }
  </script>
</head>

googlefc.callbackQueue {!Array<!Object<string, function()>> | !Array<function()> | !googlefc.CallbackQueue}

Reference to the global callback queue for asynchronous execution of messaging-related calls. The only supported way to invoke any function is by adding it to the callbackQueue.

Since different types of data become available at different times, a function should be added as a map, with one of the following strings as the key and the function to be executed as the value.

Supported keys:

Key name Usage Relative latency
CONSENT_API_READY Functions pushed to the callback queue with the CONSENT_API_READY key are executed when the APIs for supported consent frameworks are defined and callable. From this point on, execution of any subsequently added CONSENT_API_READY-keyed functions is synchronous. See sections on IAB frameworks below for framework-specific details. Low
CONSENT_DATA_READY Functions pushed to the callback queue with the CONSENT_DATA_READY key are executed when user consent gathered under a supported consent framework is known (either from a prior execution or once the user interacts with the consent message). From this point on, execution of any subsequently added CONSENT_DATA_READY-keyed functions is synchronous. High
AD_BLOCK_DATA_READY Functions pushed to the callback queue with the AD_BLOCK_DATA_READY key are executed when ad blocking data becomes available in the flow. From this point on, execution of any subsequently added AD_BLOCK_DATA_READY-keyed functions are synchronous. High
INITIAL_CCPA_DATA_READY Functions pushed to the callback queue with the INITIAL_CCPA_DATA_READY are executed when CPRA data becomes available in the flow. Note that any subsequent request for CPRA data should be obtained by directly calling the US Privacy API (__uspapi). Medium

googlefc.CallbackQueue {!Object}

Method summary:

Name Type Parameter Return type Role
push(data) number data: A key-value pair with the key as one of the data availability types and the value as a JavaScript function to be executed. The acceptable data availability keys are CONSENT_API_READY, CONSENT_DATA_READY, AD_BLOCK_DATA_READY and INITIAL_CCPA_DATA_READY. The number of commands added so far. This returns the current length of the array. Executes the function passed in, in the order in which the data becomes available, then by the order in which these functions are added to the queue.

Example:

<script>
  // Make sure that the properties exist on the window.
  window.googlefc = window.googlefc || {};
  window.googlefc.ccpa = window.googlefc.ccpa || {}
  window.googlefc.callbackQueue = window.googlefc.callbackQueue || [];

  // Queue the callback on the callbackQueue.
  googlefc.callbackQueue.push({
    'AD_BLOCK_DATA_READY':
    () => {
      if (googlefc.getAdBlockerStatus() == googlefc.AdBlockerStatusEnum.NO_AD_BLOCKER) {
        // Handle a non-ad blocking user.
      }
    }
  });
</script>

googlefc.AdBlockerStatusEnum {!Object<string, number>}

Represents the different ad blocking states of the user. The different states are:

googlefc.AdBlockerStatusEnum = {
  // Something failed, in an unknown state.
  UNKNOWN: 0,
  // The user was running an extension level ad blocker.
  EXTENSION_AD_BLOCKER: 1,
  // The user was running a network level ad blocker.
  NETWORK_LEVEL_AD_BLOCKER: 2,
  // The user was not blocking ads.
  NO_AD_BLOCKER: 3,
};

googlefc.AllowAdsStatusEnum {!Object<string, number>}

Represents the different ad blocking allow-ads states of the user. The different states are:

googlefc.AllowAdsStatusEnum = {
  // Something failed, in an unknown state.
  UNKNOWN: 0,
  // User is currently using an ad blocker, was never using an ad blocker, or
  // allowed ads, but not because they saw the Privacy & messaging message.
  ADS_NOT_ALLOWED: 1,
  // User is no longer using an ad blocker after seeing the ad blocking message.
  ADS_ALLOWED: 2,
};

googlefc.ccpa.InitialCcpaStatusEnum{!Object<string, number>}

Represents the different ad blocking allow-ads states of the user. The different states are:

googlefc.ccpa.InitialCcpaStatusEnum = {
  // Something failed, in an unknown state.
  UNKNOWN: 0,
  // CPRA does not apply to this user.
  CCPA_DOES_NOT_APPLY: 1,
  // CPPA applies to this user, and the user has not opted out yet.
  NOT_OPTED_OUT: 2,
  // CPPA applies to this user, and the user has opted out.
  OPTED_OUT: 3,
};

googlefc.ccpa.overrideDnsLink{undefined|boolean}

Set this field to true in order to hide the default Do Not Sell link and use a custom Do Not Sell link.

Example:

<script>
  // Make sure that the properties exist on the window.
  window.googlefc = window.googlefc || {};
  window.googlefc.ccpa = window.googlefc.ccpa || {}
  // Signals that the default DNS link will be overridden.
  googlefc.ccpa.overrideDnsLink = true;
</script>

Methods: explanations and examples

googlefc.getConsentStatus(): {number}


googlefc.getConsentedProviderIds(): {!Array<string>}

  1. This now always returns an empty list when called.

googlefc.showRevocationMessage(): {undefined}

Clears the current consent record and shows the consent message that is applicable for this user. The key that should be specified for this function is CONSENT_DATA_READY.

Example:

<button type="button" onclick="googlefc.callbackQueue.push({'CONSENT_DATA_READY': () => googlefc.showRevocationMessage()});">
  Click here to revoke
</button>

googlefc.getAdBlockerStatus(): {number}

Returns a value in the AdBlockerStatusEnum depending on the ad blocking status of the user. The key that should be specified for this function is AD_BLOCK_DATA_READY.

Example:

<script>
  // Make sure that the properties exist on the window.
  window.googlefc = window.googlefc || {};
  window.googlefc.ccpa = window.googlefc.ccpa || {}
  window.googlefc.callbackQueue = window.googlefc.callbackQueue || [];

  // Queue the callback on the callbackQueue.
  googlefc.callbackQueue.push({
    'AD_BLOCK_DATA_READY':
    () => {
      switch (googlefc.getAdBlockerStatus()) {
          case googlefc.AdBlockerStatusEnum.EXTENSION_LEVEL_AD_BLOCKER:
          case googlefc.AdBlockerStatusEnum.NETWORK_LEVEL_AD_BLOCKER:
            // Insert handling for cases where the user is blocking ads.
            break;
          case googlefc.AdBlockerStatusEnum.NO_AD_BLOCKER:
            // Insert handling for cases where the user is not blocking ads.
            break;
          case googlefc.AdBlockerStatusEnum.UNKNOWN:
            // Insert handling for unknown cases.
            break;
      }
    }
  });
</script>

googlefc.getAllowAdsStatus(): {number}

Returns a value in the AllowAdsStatusEnum depending on the allow-ads status of the user. The key that should be specified for this function is AD_BLOCK_DATA_READY.

Example:

<script>
  // Make sure that the properties exist on the window.
  window.googlefc = window.googlefc || {};
  window.googlefc.ccpa = window.googlefc.ccpa || {}
  window.googlefc.callbackQueue = window.googlefc.callbackQueue || [];

  // Queue the callback on the callbackQueue.
  googlefc.callbackQueue.push({
    'AD_BLOCK_DATA_READY':
    () => {
      switch (googlefc.getAllowAdsStatus()) {
        case googlefc.AllowAdsStatusEnum.ADS_NOT_ALLOWED:
          // Insert handling for cases where the user has not allowed ads.
          // The user may have never been an ad blocker.
          break;
        case googlefc.AllowAdsStatusEnum.ADS_ALLOWED:
          // Insert handling for cases where the user saw the ad blocking
          // message and allowed ads on the site.
          break;
        case googlefc.AllowAdsStatusEnum.UNKNOWN:
          // Insert handling for unknown cases.
          break;
      }
    }
  });
</script>

googlefc.ccpa.getInitialCcpaStatus(): {number}

Returns a value in the InitialCcpaStatusEnum depending on the CPRA status of the user. The key that should be specified for this function is INITIAL_CCPA_DATA_READY. Note that any subsequent request for CPRA data should be obtained by directly calling the US Privacy API (__uspapi).

Example:

<script>
  // Make sure that the properties exist on the window.
  window.googlefc = window.googlefc || {};
  window.googlefc.ccpa = window.googlefc.ccpa || {}
  window.googlefc.callbackQueue = window.googlefc.callbackQueue || [];

  // Queue the callback on the callbackQueue.
  googlefc.callbackQueue.push({
    'INITIAL_CCPA_DATA_READY':
    () => {
      switch (googlefc.ccpa.getInitialCcpaStatus()) {
        case googlefc.ccpa.InitialCcpaStatusEnum.CCPA_DOES_NOT_APPLY:
          // Insert handling for cases where the user is not CPRA eligible.
          break;
        case googlefc.ccpa.InitialCcpaStatusEnum.NOT_OPTED_OUT:
          // Insert handling for cases where the user is CPRA eligible and has
          // not opted out.
          break;
        case googlefc.ccpa.InitialCcpaStatusEnum.OPTED_OUT:
          // Insert handling for cases where the user is CPRA eligible and has
          // opted out.
          break;
      }
    }
  });
</script>

googlefc.ccpa.openConfirmationDialog(function(boolean)): {undefined}

Opens the CPRA confirmation dialog if the default Do Not Sell link is overridden. Once the user interacts with the confirmation dialog, the provided callback function is called with true if the user decides to opt-out, and false otherwise.

Example:

<script>
// This callback will be called with the user CPRA decision.
const ccpaCompletionCallback = (userOptedOut) => {
  // Insert handling for user opt-out status here.
}
// Invoke the CPRA confirmation dialog when the user clicks the link.
document.getElementById("your-custom-ccpa-do-not-sell-link").addEventListener(
  "click", () => googlefc.ccpa.openConfirmationDialog(ccpaCompletionCallback));
</script>

If you are using Google consent management solutions to gather GDPR consent under the IAB TCF v2 framework, you should use the IAB TCF v2 API.

You can use the CONSENT_API_READY callback queue key to ensure that corresponding callbacks are invoked only when the IAB TCF v2 API is defined on the page. This should be used in conjunction with the 'addEventListener' command of the IAB TCF v2 API.

Example:

<script>
  // Make sure that the properties exist on the window.
  window.googlefc = window.googlefc || {};
  window.googlefc.callbackQueue = window.googlefc.callbackQueue || [];

  // Queue the callback using the CONSENT_API_READY key on the callbackQueue.
  window.googlefc.callbackQueue.push({
    'CONSENT_API_READY':
    () => __tcfapi('addEventListener', 2.2, (data, success) => {
      // Do something with consent data value; this callback may be invoked
      // multiple times as user completes consent flow.
    })
  });
</script>

You can use the CONSENT_DATA_READY callback queue key to ensure that corresponding callbacks are invoked only when user consent is collected and accessible using the IAB TCF v2 API. This can be used in conjunction with the 'addEventListener' command - the data provided in the first invocation of your provided callback will contain the user's consent selections (as long as TCF v2 applies to this user). Note that with the release of TCF v2.2, the 'getTCData' command is now deprecated.

Example:

<script>
  // Make sure that the properties exist on the window.
  window.googlefc = window.googlefc || {};
  window.googlefc.callbackQueue = window.googlefc.callbackQueue || [];

  // Queue the callback using the CONSENT_DATA_READY key on the callbackQueue.
  window.googlefc.callbackQueue.push({
    'CONSENT_DATA_READY':
    () => __tcfapi('addEventListener', 2.2, (data, success) => {
      // Do something with consent data value; this callback may be invoked
      // multiple times if user consent selections change.
    })
  });
</script>

Using Google consent management solutions with the IAB GPP framework for CPRA

If you are using Google consent management solutions to gather CPRA opt-out under the IAB GPP framework, you should use the IAB GPP API.

Due to the opt out nature of the CPRA regulation, you may use either the CONSENT_API_READY or CONSENT_DATA_READY callback queue key to ensure that the IAB GPP API is callable and returning consent data at the time that callbacks are invoked.

<script>
  // Make sure that the properties exist on the window.
  window.googlefc = window.googlefc || {};
  window.googlefc.ccpa = window.googlefc.ccpa || {}
  window.googlefc.callbackQueue = window.googlefc.callbackQueue || [];

  // Queue the callback on the callbackQueue.
  window.googlefc.callbackQueue.push({
    'CONSENT_DATA_READY':
    () => __uspapi('getUSPData', 1, (data, success) => {
      // Do something with consent data value.
    })
  });
</script>

Using Google consent management solutions with the IAB GPP framework for CPRA with a custom Do Not Sell link

If you are using Google consent management solutions to gather CPRA opt-out under the IAB GPP framework, it is possible to provide a custom Do Not Sell link by setting the googlefc.ccpa.overrideDnsLink flag to true.

<script>
  // Make sure that the properties exist on the window.
  window.googlefc = window.googlefc || {};
  window.googlefc.ccpa = window.googlefc.ccpa || {}
  window.googlefc.callbackQueue = window.googlefc.callbackQueue || [];

  // Signals that the default DNS link will be overridden.
  window.googlefc.ccpa.overrideDnsLink = true;

  // Register the callback for the initial CPRA data.
  window.googlefc.callbackQueue.push({
      'INITIAL_CCPA_DATA_READY': () => {
        if (googlefc.ccpa.getInitialCcpaStatus() ===
            googlefc.ccpa.InitialCcpaStatusEnum.NOT_OPTED_OUT) {
          // TODO: Display custom CPRA Do Not Sell link here.
        }
      }
    });
</script>

This ensures that the default Do Not Sell link does not render. Note that you are responsible for rendering your own Do Not Sell link in order to be compliant with CPRA. Then, you need to handle the user interaction with your custom Do Not Sell link by invoking the CPRA confirmation dialog.

<script>
// This callback will be called with the user CPRA decision.
const ccpaCompletionCallback = (userOptedOut) => {
  if (userOptedOut) {
    // TODO: Hide custom CPRA Do Not Sell link here.
  }
}
// Invoke the CPRA confirmation dialog when the user clicks the link.
document.getElementById("your-custom-ccpa-do-not-sell-link").addEventListener(
  "click", () => googlefc.ccpa.openConfirmationDialog(ccpaCompletionCallback));
</script>