chrome.declarativeContent

Description

Use thechrome.declarativeContent API to take actions depending on the content of a page, without requiring permission to read the page's content.

Permissions

declarativeContent

Concepts and usage

Key term: Anextension'saction controls the extension's toolbar icon.

The Declarative Content API lets you enable your extension's action depending on the URL of aweb page, or if a CSS selector matches an element on the page, without needing toaddhost permissions or inject acontent script.

Use theactiveTab permission to interact with a page after the user clicks on theextension's action.

Rules

Rules consists of conditions and actions. If any of the conditions is fulfilled, all actions areexecuted. The actions aresetIcon() andshowAction().

ThePageStateMatcher matches web pages if and only if all listedcriteria are met. It can match apage url, acss compound selectoror thebookmarked state of a page. The following rule enablesthe extension's action on Google pages when a password field is present:

letrule1={conditions:[newchrome.declarativeContent.PageStateMatcher({pageUrl:{hostSuffix:'.google.com',schemes:['https']},css:["input[type='password']"]})],actions:[newchrome.declarativeContent.ShowAction()]};
Success: All conditions and actions are created using a constructor as shown in the previous example.

To also enable the extension's action for Google sites with a video, you can add a secondcondition, as each condition is sufficient to trigger all specified actions:

letrule2={conditions:[newchrome.declarativeContent.PageStateMatcher({pageUrl:{hostSuffix:'.google.com',schemes:['https']},css:["input[type='password']"]}),newchrome.declarativeContent.PageStateMatcher({css:["video"]})],actions:[newchrome.declarativeContent.ShowAction()]};

TheonPageChanged event tests whether any rule has at least one fulfilledcondition and executes the actions. Rules persist across browsing sessions; therefore, duringextension installation time you should first useremoveRules to clearpreviously installed rules and then useaddRules to register new ones.

chrome.runtime.onInstalled.addListener(function(details){chrome.declarativeContent.onPageChanged.removeRules(undefined,function(){chrome.declarativeContent.onPageChanged.addRules([rule2]);});});
Note: You should always register or unregister rules in bulk because each of these operations recreatesinternal data structures. This re-creation is computationally expensive but facilitates a fastermatching algorithm.

With theactiveTab permission, your extension won't display any permissionwarnings and when the user clicks the extension action, it will only run on relevant pages.

Page URL matching

ThePageStateMatcher.pageurl matches when the URL criteria are fulfilled. Themost common criteria are a concatenation of either host, path, or URL, followed by Contains, Equals, Prefix, orSuffix. The following table contains a few examples:

CriteriaMatches
{ hostSuffix: 'google.com' }All Google URLs
{ pathPrefix: '/docs/extensions' }Extension docs URLs
{ urlContains: 'developer.chrome.com' }All chrome developers docs URLs

All criteria are case sensitive. For a complete list of criteria, seeUrlFilter.

CSS Matching

PageStateMatcher.css conditions must becompound selectors,meaning that you can't includecombinators like whitespace or ">" in yourselectors. This helps Chrome match the selectors more efficiently.

Compound Selectors (OK)Complex Selectors (Not OK)
adiv p
iframe.special[src^='http']p>span.highlight
ns|*p + ol
#abcd:checkedp::first-line

CSS conditions only match displayed elements: if an element that matches your selector isdisplay:none or one of its parent elements isdisplay:none, it doesn't cause the condition tomatch. Elements styled withvisibility:hidden, positioned off-screen, or hidden by other elementscan still make your condition match.

Bookmarked state matching

ThePageStateMatcher.isBookmarked condition allows matching of thebookmarked state of the current URL in the user's profile. To make use of this condition the"bookmarks" permission must be declared in the extensionmanifest.

Types

Type

ImageData

PageStateMatcher

Matches the state of a web page based on various criteria.

Properties

  • constructor

    void

    Theconstructor function looks like:

    (arg: PageStateMatcher) => {...}

  • css

    string[] optional

    Matches if all of the CSS selectors in the array match displayed elements in a frame with the same origin as the page's main frame. All selectors in this array must becompound selectors to speed up matching. Note: Listing hundreds of CSS selectors or listing CSS selectors that match hundreds of times per page can slow down web sites.

  • isBookmarked

    boolean optional

    Chrome 45+

    Matches if the bookmarked state of the page is equal to the specified value. Requres thebookmarks permission.

  • pageUrl

    UrlFilter optional

    Matches if the conditions of theUrlFilter are fulfilled for the top-level URL of the page.

RequestContentScript

Declarative event action that injects a content script.

WARNING: This action is still experimental and is not supported on stable builds of Chrome.

Properties

  • constructor

    void

    Theconstructor function looks like:

    (arg: RequestContentScript) => {...}

  • allFrames

    boolean optional

    Whether the content script runs in all frames of the matching page, or in only the top frame. Default isfalse.

  • css

    string[] optional

    Names of CSS files to be injected as a part of the content script.

  • js

    string[] optional

    Names of JavaScript files to be injected as a part of the content script.

  • matchAboutBlank

    boolean optional

    Whether to insert the content script onabout:blank andabout:srcdoc. Default isfalse.

SetIcon

Declarative event action that sets the n-dip square icon for the extension'spage action orbrowser action while the corresponding conditions are met. This action can be used withouthost permissions, but the extension must have a page or browser action.

Exactly one ofimageData orpath must be specified. Both are dictionaries mapping a number of pixels to an image representation. The image representation inimageData is anImageData object; for example, from acanvas element, while the image representation inpath is the path to an image file relative to the extension's manifest. Ifscale screen pixels fit into a device-independent pixel, thescale * n icon is used. If that scale is missing, another image is resized to the required size.

Properties

  • constructor

    void

    Theconstructor function looks like:

    (arg: SetIcon) => {...}

  • imageData

    ImageData | object optional

    Either anImageData object or a dictionary {size -> ImageData} representing an icon to be set. If the icon is specified as a dictionary, the image used is chosen depending on the screen's pixel density. If the number of image pixels that fit into one screen space unit equalsscale, then an image with sizescale * n is selected, wheren is the size of the icon in the UI. At least one image must be specified. Note thatdetails.imageData = foo is equivalent todetails.imageData = {'16': foo}.

ShowAction

Chrome 97+

A declarative event action that sets the extension's toolbaraction to an enabled state while the corresponding conditions are met. This action can be used withouthost permissions. If the extension has theactiveTab permission, clicking the page action grants access to the active tab.

On pages where the conditions are not met the extension's toolbar action will be grey-scale, and clicking it will open the context menu, instead of triggering the action.

Properties

ShowPageAction

Deprecated since Chrome 97

Please usedeclarativeContent.ShowAction.

A declarative event action that sets the extension'spage action to an enabled state while the corresponding conditions are met. This action can be used withouthost permissions, but the extension must have a page action. If the extension has theactiveTab permission, clicking the page action grants access to the active tab.

On pages where the conditions are not met the extension's toolbar action will be grey-scale, and clicking it will open the context menu, instead of triggering the action.

Properties

Events

onPageChanged

Provides theDeclarative Event API consisting ofaddRules,removeRules, andgetRules.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-08-11 UTC.