Topics API developer guide

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

Published on Updated on

Implementation status

Try the Topics API

Topics is not currently available by default in any version of Chrome, but you can activate the API in two ways, as a single user or at scale:

  • The Topics API demo allows you to try it out as a single user.
  • The Topics origin trial allows you to try the API at scale with your website users.

Try the demo

The demo of the Topics API is at topics-demo.glitch.me. It explains how to try out and debug the API for a single user.

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

Test Topics in an origin trial

A Privacy Sandbox Relevance and Measurement origin trial has been made available in Chrome Beta 101.0.4951.26 and above on desktop for the Topics, FLEDGE, and Attribution Reporting APIs.

Get and set topics

The Topics JavaScript API has one method: document.browsingTopics(), which is used to get and set Topics. It 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 currently set to one week.

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

  • configVersion: a string identifying the current Topics API configuration
  • modelVersion: a string identifying the machine-learning classifier used to infer topics for the site
  • taxonomyVersion: a string identifying the set of topics currently in use by the browser
  • topic: a number identifying the topic in the taxonomy
  • version: a string combining the configVersion and the modelVersion

The parameters described in this article, 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');
Caution

Feature support on the current page isn't a guarantee that an API is usable: the user may have disabled the API via browser settings, or they may have other settings that prevent the API from being used. To protect user privacy, there is no way to check for these other settings programmatically.

Access topics with the JavaScript API

Here is a basic example of possible API usage to access topics for the current user. To keep it simple, there's no error handling.

// Get the array of top topics for this user.
const topics = await document.browsingTopics();

// Request an ad creative.
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.

Access topics without modifying state

By default, document.browsingTopics() records a topic observation whenever it returns topics. From Chrome 108, the document.browsingTopics() method can be passed an optional argument to skip this recording: {skipObservation:true}.

In other words, the call will not cause the current page to be included in the weekly epoch calculation, nor will it update the list of topics observed for the caller.

Use headers to access and observe topics

You can access and observe topics with the help of request and response headers. Headers can be much more performant than calling the JavaScript API.

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

Inclusion of the Topics header in XHR requests is only available temporarily, and support will be removed in the future.

You can mark topics provided by request headers as observed by setting an Observe-Browsing-Topics: ?1 header on the response to the request. The browser will then use those topics included in the request header to calculate topics of interest for a user.

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

  • fetch(): Use headers to call topics when the fetch() request is made to an ad server. For more on this technique, check out the demo.
  • iframe attributes: Send request headers with document requests by either adding the browsingtopics attribute to an iframe or with the equivalent IDL attribute: iframe.browsingTopics = true. The iframe source should be the registrable domain for topic observation.
    • For example: <iframe src="https://example.com" browsingtopics></iframe>
    • This is available from Chrome M114 and onward.

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 will not modify state for the caller unless there is a corresponding response header. That is, the topic of the page won't be considered observed, nor will it affect the user's topic calculation for the next epoch.
  • The response header is only honored if the corresponding request included the topics header (or would have included the header, if the request wasn't empty).
  • The URL of the request provides the registrable domain used for topic observation.

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.

The chrome://topics-internals page is new. The design and functionality are still under discussion. We're currently iterating and improving the design 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 Topics IDs, random and real topic assignments, and taxonomy and model versions.

In this example, 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 below, 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-demo.glitch.me recommends using the following flags:

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

Each parameter, its default value, and its purpose is explained in the list below.

Chrome flags

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

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

PrivacySandboxSettings3
Default value: disabled
Enables the third 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 7 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 max number of observed-by context domains to keep for each top topic. The intent is to cap the in-use memory.

BrowsingTopics:max_number_of_api_usage_context_entries_to_load_per_epoch
Default value: 100000
The max 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 the peak memory usage.

BrowsingTopics:max_number_of_api_usage_context_domains_to_store_per_page_load
Default value: 30
The max 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 be usually fine for local testing, but in some situations could leave the browser in an inconsistent state and/or could let the browser crash, e.g. 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 will not 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 Permission Policy header to control third-party access to the Topics API.

Use self and any domains you would like to allow access to the API as parameters.

For example, to completely disable use of the Topics API within all browsing contexts except for your own origin and those whose origin is https://example.com, set the following HTTP response header:

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

Next steps

Find out more

Engage and share feedback

Updated on Improve article

We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.