IHOR.DEVKNOWLEDGE_BASE
MENU

~/blog / Extensions / declarative-content-rules-for-chrome-extensions.md

// guide · 3 min read

Declarative Content Rules for Chrome Extensions

Enable a Chrome action on relevant pages with declarativeContent rules, without continuous DOM access; understand compound selectors and persistent rule updates.

Quick answer

Use declarativeContent when the browser can decide whether your toolbar action is relevant from URL criteria or supported CSS selectors. Declare the permission, disable the action by default, and install rules that enable it when conditions match. The rule does not return page text or grant unrestricted access.

A rule can make an explicit page-inspection tool discoverable on suitable pages while leaving actual inspection behind a user invocation and its own access rules. It is different from declarativeNetRequest, which concerns network rules rather than toolbar relevance.

Practical implementation steps

  1. State the relevance condition, such as a supported host or the presence of a video element. Use PageStateMatcher constructors and ShowAction, not obsolete Manifest V2 page-action snippets.
  2. Distinguish condition logic: every criterion within one matcher must hold, while any matcher in a rule’s conditions array can activate its actions. Separate matchers can unintentionally broaden a rule.
  3. Use supported compound CSS selectors. video.preview is a compound selector; main video includes a combinator and is not supported here. Avoid hundreds of selectors that add unnecessary matching work.
  4. Install or replace rules on installation/update. Rules persist across browser sessions, so recreating them on every worker boot is unnecessary. Give owned rules stable IDs and remove obsolete versions before adding replacements.
  5. Verify matching and nonmatching pages. CSS matching concerns displayed elements under documented conditions; visibility:hidden is not the same as display:none. An enabled action is a relevance hint, not proof that your operation can run on every frame.

Font Picker illustrates a page-inspection job that could benefit from contextual relevance, but its public record does not establish use of this API. Prefer a simple URL rule if DOM criteria add no meaningful product distinction.

Implementation example

With an action and declarativeContent permission, this worker enables the action on HTTPS example.com pages containing a displayed video. Additional activeTab/scripting permissions would be separate choices for an invoked inspection.

chrome.runtime.onInstalled.addListener(() => {
  chrome.action.disable().catch(console.error);
  chrome.declarativeContent.onPageChanged.removeRules(["video-page"], () => {
    if (chrome.runtime.lastError) {
      console.error(chrome.runtime.lastError.message);
      return;
    }
    chrome.declarativeContent.onPageChanged.addRules([{
      id: "video-page",
      conditions: [new chrome.declarativeContent.PageStateMatcher({
        pageUrl: { hostEquals: "example.com", schemes: ["https"] },
        css: ["video"],
      })],
      actions: [new chrome.declarativeContent.ShowAction()],
    }], () => {
      if (chrome.runtime.lastError) console.error(chrome.runtime.lastError.message);
    });
  });
});

The exact host example intentionally avoids treating a suffix filter as an authorization boundary. Keep privileged operation authorization separate even when the rule restricts the visible action.

Tradeoffs and alternatives

Declarative relevance avoids a continuously running content script just to inspect eligibility. A content script remains necessary for richer page logic or unsupported selectors. Do not use experimental RequestContentScript as a stable production injection strategy; the reference marks it unsupported on stable Chrome.

Common mistakes

  • Confusing network rules with page-relevance rules.
  • Using complex CSS selectors with spaces or > combinators.
  • Reinstalling persistent rules on every worker start.
  • Treating ShowAction as permission to read arbitrary page data.

Production checklist

  • Rule logic matches the intended AND/OR behavior.
  • Selectors are supported compound selectors.
  • Rule replacement preserves unrelated rule ownership.
  • Matching and nonmatching states are checked.
  • Invocation access is justified independently.

FAQ

Does matching give me the matched element?

No. It activates a declared action; it is not a DOM-query response API.

Do rules survive worker termination?

Yes. Manage them deliberately during installation/update instead of relying on worker memory.

When should I avoid this API?

When the action is useful on almost every supported page or when deciding eligibility requires richer logic than the API supports. A clear unavailable-state message may be simpler.

Primary sources

Ihor Kharchyshyn

Independent full-stack product engineer writing source-backed implementation guides for browser extensions and modern web products.

Need this implemented in a real product?

Browser tools with a clear purpose, focused permissions, and a maintainable Manifest V3 architecture.