Topics API developer guide

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

Published on Updated on

Translated to: Español, Português, 한국어, 中文, Pусский, 日本語

Important

The Privacy Sandbox Relevance and Measurement origin trial ended September 20, 2023 and the APIs are now available for 99% of Chrome users, and origin trial enrollment has closed. To keep abreast of the percentage of users each API is enabled for, refer to the Chrome status graphs.

Implementation status

Try the demo

The Topics API demo allows you to try it out as a single user.

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.

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.

try {
// 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.

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

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.
Important

CSP directives may disallow execution of third-party code included on a page, such as a fetch() call in an ad tech script.

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.

There is a new improved taxonomy, updated June 15, 2023 in which we added 280 commercially focused categories, like "Athletic Apparel", "Mattresses", and "Luxury Travel," while removing 160 categories including topics like "Civil Engineering" and "Equestrian". Examples here use version 1 of the taxonomy. Chrome will begin using the new taxonomy later this year, but you can view it here, and provide feedback.

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,PrivacySandboxSettings4,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, 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/or could result in a 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 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

Updated on Improve article

This site uses cookies to deliver and enhance the quality of its services and to analyze traffic. If you agree, cookies are also used to serve advertising and to personalize the content and advertisements that you see. Learn more about our use of cookies.