Topics API Developer's Guide

Learn how to work with the API, including how to use Chrome flags for testing.

Implementation status

  • The Topics API has completed the public discussion phase and is currently available to 99 percent of users, scaling up to 100 percent.
  • To provide your feedback on the Topics API, create an Issue on the Topics explainer or participate in discussions in the Improving Web Advertising Business Group. The explainer has a number of open questions that still require further definition.
  • The Privacy Sandbox timeline provides implementation timelines for the Topics API and other Privacy Sandbox proposals.
  • Topics API: latest updates details changes and enhancements to the Topics API and implementations.

Try the demo

There are two Topics API demos that enable you to try out Topics as a single user.

You can also run the Topics colab to try out the Topics classifier model.

Use the JavaScript API to access topics and record them as observed

The Topics JavaScript API has one method: document.browsingTopics(). This has two purposes:

  • Tell the browser to record the current page visit as having been observed for the caller, so this can later be used to calculate topics for the user (for the caller).
  • Access topics for the user that have been observed by the caller.

The method returns a promise that resolves to an array of up to three topics, one for each of the three most recent epochs, in random order. An epoch is a period of time, set to one week in Chrome's implementation.

Each topic object in the array returned by document.browsingTopics() has these properties:

  • configVersion: a string identifying the current Topics API configuration, for example chrome.2
  • modelVersion: a string identifying the machine-learning classifier used to infer topics for the site, for example 4
  • taxonomyVersion: a string identifying the set of topics used by the browser, for example 2
  • topic: a number identifying the topic in the taxonomy, for example 309
  • version: a string concatenating configVersion, taxonomyVersion, and modelVersion, for example chrome.2:2:4

The parameters described in this guide, and details of the API (such as taxonomy size, the number of topics calculated per week and the number of topics returned per call) are subject to change as we incorporate ecosystem feedback and iterate on the API.

Detect support for document.browsingTopics

Before using the API, check if it's supported by the browser and available in the document:

'browsingTopics' in document && document.featurePolicy.allowsFeature('browsing-topics') ?
 console.log('document.browsingTopics() is supported on this page') :
 console.log('document.browsingTopics() is not supported on this page');

Access topics with the JavaScript API

Here is a basic example of possible API usage to access topics for the current user.

try {
  // Get the array of top topics for this user.
  const topics = await document.browsingTopics();
  
  // Request an ad creative, providing topics information.
  const response = await fetch('https://ads.example/get-creative', {
   method: 'POST',
   headers: {
     'Content-Type': 'application/json',
   },
   body: JSON.stringify(topics)
  })
  
  // Get the JSON from the response.
  const creative = await response.json();
  
  // Display ad.

} catch (error) {
  // Handle error.
}

Access topics without modifying state

document.browsingTopics() returns topics observed by the caller for the current user. By default, the method also causes the browser to record the current page visit as observed by the caller, so it can later be used in topics calculation. From Chrome 108, the method can be passed an optional argument to skip the page visit from being recorded: {skipObservation:true}.

In other words, {skipObservation:true} means the method call won't cause the current page to be included in the calculation of topics.

Use headers to access topics and mark them as observed

You can access topics, and also mark page visits as observed, with the help of request and response headers.

Using the header approach can be much more performant than using the JavaScript API, since the API requires creating a cross-origin iframe and making a document.browsingTopics() call from it. (A cross-origin iframe must be used for the call, because the context from which the API is invoked is used to ensure the browser returns the topics appropriate to the caller.) The Topics explainer has further discussion: Should there be a way to send topics using Fetch as a request header? .

Topics can be accessed from the Sec-Browsing-Topics header of a fetch() or XHR request.

Setting an Observe-Browsing-Topics: ?1 header on the response to the request causes the browser to record the current page visit as observed by the caller, so it can later be used in topics calculation.

Topics can be accessed and observed with HTTP headers in two ways:

  • fetch(): Add {browsingTopics: true} to the options parameter of a fetch() request. The Topics header demo shows a simplified example of this.
  • iframe attribute: Add the browsingtopics attribute to an <iframe> element, or set the equivalent JavaScript property iframe.browsingTopics = true. The registrable domain of the iframe source is the caller domain: for example, for <iframe src="https://example.com" browsingtopics></iframe>: the caller is example.com.

Some additional notes about headers:

  • Redirects will be followed, and the topics sent in the redirect request will be specific to the redirect URL.
  • The request header won't modify state for the caller unless there is a corresponding response header. That is, without the response header, the page visit won't be recorded as observed, so it won't affect the user's topic calculation for the next epoch.
  • The response header is only honored if the corresponding request included the topics header.
  • The URL of the request provides the registrable domain that is recorded as the caller domain.

Debug your API implementation

The chrome://topics-internals page is available in Chrome on desktop once you enable the Topics API. This displays topics for the current user, topics inferred for hostnames, and technical information about the API implementation. We're iterating and improving the design of the page based on developer feedback: add your feedback at bugs.chromium.org.

View topics calculated for your browser

Users can view information about topics observed for their browser during the current and previous epochs by viewing chrome://topics-internals.

The chrome://topics-internals page with Topics State panel selected.
The chrome://topics-internals page Topics State panel shows topic IDs, random and real topic assignments, and taxonomy and model versions.

This screenshot shows that recently visited sites include topics-demo-cats.glitch.me and cats-cats-cats-cats.glitch.me. This causes the Topics API to select Pets and Cats as two of the top topics for the current epoch. The remaining three topics have been chosen at random, since there is not enough browsing history (on sites that observe topics) to provide five topics.

The Observed-by context domains (hashed) column provides the hashed value of a hostname for which a topic was observed.

View topics inferred for hostnames

You can also view the topics inferred by the Topics classifier model for one or more hostnames in chrome://topics-internals.

The chrome://topics-internals page with Classifier panel selected.
The chrome://topics-internals page Classifier panel shows topics selected, hosts visited, and model version and path.

The current implementation of the Topics API infers topics from hostnames only; not from any other part of a URL.

Use hostnames only (without protocol or path) to view inferred topics from the chrome://topics-internals Classifier. chrome://topics-internals will display an error if you attempt to include a "/" in the Host field.

View Topics API information

You can find information about the Topics API implementation and settings, such as the taxonomy version and epoch duration, in chrome://topics-internals. These values reflect default settings for the API or parameters successfully set from the command line. This may be helpful to confirm that command line flags have worked as expected.

In the example, time_period_per_epoch has been set to 15 seconds (the default is seven days).

chrome://topics-internals page with Features and Parameters panel selected.
The chrome://topics-internals Features and Parameters panel shows enabled features, time per epoch, number of epochs to use to calculate topics, taxonomy version, and other settings.

The parameters shown in the screenshot correspond to flags that can be set when running Chrome from the command line. For example, the demo at topics-fetch-demo.glitch.me recommends using the following flags:

--enable-features=BrowsingTopics,BrowsingTopicsParameters:time_period_per_epoch/15s/max_epoch_introduction_delay/3s,PrivacySandboxAdsAPIsOverride,PrivacySandboxSettings3,OverridePrivacySandboxSettingsLocalTesting

The following list explains each parameter, its default value, and its purpose.

Chrome flags

BrowsingTopics
Default value: enabled
Whether the Topics API is enabled.

PrivacySandboxAdsAPIsOverride
Default value: enabled
Enables ads APIs: Attribution Reporting, Protected Audience, Topics, Fenced Frames.

PrivacySandboxSettings4
Default value: disabled
Enables the fourth release of the Privacy Sandbox UI settings.

OverridePrivacySandboxSettingsLocalTesting
Default value: enabled
If enabled, the browser no longer requires the underlying settings to be enabled for enabling the Privacy Sandbox features.

BrowsingTopicsBypassIPIsPubliclyRoutableCheck
Default value: disabled
If enabled, the check for whether the IP address is publicly routable will be bypassed when determining the eligibility for a page to be included in topics calculation.

BrowsingTopics:number_of_epochs_to_expose
Default value: 3
The number of epochs from where to calculate the topics to give to a requesting context. The browser will internally keep up to N+1 epochs.

BrowsingTopics:time_period_per_epoch
Default value: 7d-0h-0m-0s
Duration of each epoch. For debugging, it can be useful to set this to (say) 15 seconds, rather than the default seven days.

BrowsingTopics:number_of_top_topics_per_epoch
Default value: 5
Number of topics calculated per epoch.

BrowsingTopics:use_random_topic_probability_percent
Default value: 5
Probability that an individual topic within an epoch is one returned at random from the entire taxonomy of topics. The randomness is sticky to an epoch and site.

BrowsingTopics:number_of_epochs_of_observation_data_to_use_for_filtering
Default value: 3
How many epochs of API usage data (i.e. topics observations) will be used for filtering the topics for a calling context.

BrowsingTopics:max_number_of_api_usage_context_domains_to_keep_per_topic
Default value: 1000
The maximum number of observed-by context domains to keep for each top topic. The intent is to cap in-use memory.

BrowsingTopics:max_number_of_api_usage_context_entries_to_load_per_epoch
Default value: 100000
The maximum number of entries allowed to be retrieved from the database for each query for the API usage contexts. The query will occur once per epoch at topics calculation time. The intent is to cap peak memory usage.

BrowsingTopics:max_number_of_api_usage_context_domains_to_store_per_page_load
Default value: 30
The maximum number of API usage context domains allowed to be stored per page load.

BrowsingTopics:config_version
Default value: 1
Encodes the Topics API configuration parameters. Each version number should only be mapped to one configuration set. Updating the configuration parameters without updating the config_version should usually be fine for local testing, but in some situations could leave the browser in an inconsistent state and could result in a browser crash, for example updating the number_of_top_topics_per_epoch.

BrowsingTopics:taxonomy_version
Default value: 1
The taxonomy version used by the API.

Opt out your site

You can opt out of topic calculation for specific pages on your site by including the Permissions-Policy: browsing-topics=() Permissions-Policy header on a page to prevent topics calculation for all users on that page only. Subsequent visits to other pages on your site won't be affected: if you set a policy to block the Topics API on one page, this won't affect other pages.

You can also control which third parties have access to topics on your page by using the Permissions-Policy header to control third-party access to the Topics API. As parameters to the header, use self and any domains you would like to allow access to the API. For example, to completely disable use of the Topics API within all browsing contexts except for your own origin and https://example.com, set the following HTTP response header:

Permissions-Policy: browsing-topics=(self "https://example.com")

Next steps

Find out more

Engage and share feedback