@guardian/consent-manager

中文文档
2.3.1发布于 2026/11/12TypeScriptESM + CJS构建来源已验证近 30 天下载 2.1万

Consent Manager for the Guardian

原始使用文档
文档目录20 节
  1. Installation
  2. Bundling
  3. Table of Contents
  4. Managing Consent
  5. cmp.init(options)
  6. cmp.hasInitialised()
  7. cmp.willShowPrivacyMessage()
  8. cmp.willShowPrivacyMessageSync()
  9. cmp.showPrivacyManager()
  10. Using Consent
  11. onConsentChange(callback, final?)
  12. onConsent()
  13. getConsentFor(vendor, consentState)
  14. Disabling Consent
  15. cmp.__disable()
  16. cmp.__enable()
  17. cmp.__isDisabled()
  18. Manually
  19. Using Cypress
  20. Development

Consent Management Platform

The Guardian's consent management platform.

npm (scoped) ES version Types Coverage Status

Consent management for *.theguardian.com.

The Guardian CMP handles applying the USNAT to users in the USA, Sourcepoint Global Enterprise to Aus and TCFv2 to everyone else.

Installation

Generic badge

yarn add @guardian/consent-manager

or

npm install @guardian/consent-manager

then

import { getConsentFor, ...etc } from '@guardian/consent-manager';

Bundling

This package uses ES2020.

If your target environment does not support that, make sure you transpile this package when bundling your application.

Table of Contents

import { cmp } from '@guardian/consent-manager';

cmp.init(options)

returns: void

Adds the relevent privacy framework to the page. It must be called to enable privacy management. If necessary, it will also display the initial privacy message.

options.country

type: CountryCode from @guardian/libs values: e.g. GB, US, AU, …

Declare which country your user is in. Required – throws an error if it's missing.

options.pubData

type: Object

Optional additional parameters for reporting.

pubData.pageViewId

type: string

Optional value identifying the unique pageview associated with this instance of the CMP.

Will be used to link back to a browserId for further reporting; if possible this should be available via the pageview table.

Example

cmp.init({
    country: 'GB',
    pubData: {
        pageViewId: 'jkao3u2kcbaqk',
    },
});

cmp.hasInitialised()

returns: boolean

Returns true if the CMP has initialised.

cmp.willShowPrivacyMessage()

returns: Promise<Boolean>

Returns a promise that resolves to true if the CMP will show the initial privacy message once it has initialised, or false if not.

Example

cmp.willShowPrivacyMessage()
    .then(willShow =>
        if (willShow) {
            console.log("a privacy message will show as soon as it's ready");
            // e.g. don't show any other banners
        } else {
            console.log('a privacy message will not be shown');
            // e.g. show another banner if you like
        }
    );

cmp.willShowPrivacyMessageSync()

returns: Boolean

You almost always want to use the async version above.

Returns true if the CMP has shown, is showing or will show the initial privacy message. Returns false otherwise.

Throws an error if the CMP has not been initialised.

Example

if (cmp.hasInitialised()) {
    if (cmp.willShowPrivacyMessageSync()) {
        // do something
    }
}

cmp.showPrivacyManager()

Displays an interface that allows users to manage their privacy settings at any time.

Example

cmp.showPrivacyManager();
import {
    onConsent,
    onConsentChange,
    getConsentFor,
} from '@guardian/consent-manager';

onConsentChange(callback, final?)

returns: void

An event listener that invokes callbacks whenever the consent state:

  • is acquired (e.g. after initialising)
  • changes (eg. if a user changes their privacy preferences)

If the consent state has already been acquired when onConsentChange is called, the callback will be invoked immediately.

Passing true for the optional final parameter guarantees that the callback will be executed after all other callbacks that haven't been registered with the flag when consent state changes. If more than one callback registered with final = true, they will be executed in the order in which they were registered when consent changes.

callback(consentState)

type: function

Reports the user's privacy preferences.

consentState.tcfv2

type: Object or undefined

Reports the user's preferences for each of the TCFv2 purposes, the last CMP event status, custom vendor consents, flag if GDPR applies, the TC string and addtlConsent string.

If the user is either in the USA or Australia, it will be undefined.

Unlike the __tcfapi, all ten consents will have a set boolean value, defaulting to false where no explicit consent was given.

{
    gdprApplies: Boolean | undefined, // true - GDPR Applies, false - GDPR Does not apply, undefined - unknown whether GDPR Applies
    tcString: String, // 'base64url-encoded TC string with segments'
    addtlConsent: String, // Google AC string
    eventStatus: String, // 'tcloaded' | 'cmpuishown' | 'useractioncomplete'
    consents: {
        1: Boolean,
        2: Boolean,
        /* … */
        9: Boolean,
        10: Boolean,
    },

    vendorConsents: {
        'abcdefghijklmnopqrstuvwx': Boolean,
        'yz1234567890abcdefghijkl': Boolean,
        'mnopqrstuvwxyz1234567890': Boolean,
        // Sourcepoint IDs, etc.
    }
}
consentState.usnat

type: Object or undefined

Reports whether user has withdrawn consent to sell their data in the USA.

If the user is not in the USA, it will be undefined.

{
    doNotSell: Boolean;
    signalStatus: 'ready';
}
consentState.aus

type: Object or undefined

Reports whether user has withdrawn consent to personalised advertising in Australia.

If the user is not in Australia, it will be undefined.

{
    personalisedAdvertising: Boolean, // True by default
}
consentState.canTarget

type: boolean

If the user can be targeted for personalisation according to the active consent framework.

For example canTarget would be true in the following scenarios:

  • for USNAT if the user has not clicked "do not sell",
  • for AUS if the user has not opted out of personalised advertising
  • for TCFv2 if the user has given consent for all purposes
consentState.framework

type: string | null

The active consent framework e.g. "usnat", "aus", "tcfv2" or null.

Example

import { onConsentChange } from '@guardian/consent-manager';

onConsentChange(({ tcfv2, usnat, aus }) => {
    if (tcfv2) {
        console.log(tcfv2); // { 1: true || false, 1: true || false, ... }
    }

    if (usnat) {
        console.log(usnat); // { doNotSell: true || false }
    }

    if (aus) {
        console.log(aus); // { personalisedAdvertising: true || false }
    }
});

onConsent()

A promise wrapper around onConsentChange that resolves the initial consent state.

This will only resolve once whereas callbacks passed to onConsentChange are executed each time consent state changes. Avoid using this function in contexts where subsequent consent states must be listened for.

returns: Promise<ConsentState>

getConsentFor(vendor, consentState)

returns: boolean

Gets the consent for a given vendor.

vendor

type: string

Supported vendors

TCFV2 vendors

  • "a9"
  • "acast"
  • "braze"
  • "comscore"
  • "criteo"
  • "google-analytics"
  • "google-mobile-ads"
  • "google-tag-manager"
  • "googletag"
  • "ias"
  • "inizio"
  • "ipsos"
  • "magnite" (do not use until contract signed)
  • "mparticle"
  • "nielsen"
  • "ophan"
  • "permutive"
  • "prebid"
  • "qm" (Quantum Metric)
  • "redplanet" (Australia only)
  • "remarketing"
  • "sentry"
  • "teads"
  • "twitter"
  • "youtube-player"

Aus only Vendors

  • "redplanet"
If the vendor you need is missing, please [raise an issue](https://github.com/guardian/consent-management-platform/issues) (or a PR!).

consentState

type: Object

The consent object passed to the onConsentChange callback.

Example

import { onConsentChange, getConsentFor } from '@guardian/consent-manager';

onConsentChange((consentState) => {
    const ga = getConsentFor('google-analytics', consentState); // true
    const comscore = getConsentFor('comscore', consentState); // false

    // throws error
    const eowifnwoeifjoweinf = getConsentFor('eowifnwoeifjoweinf', consentState);

    // you can still use the consent state for a more complicated task
    const complexConsentCondition = myComplexConsentTask(consentState);
});

It is possible to disable the CMP entirely in the current browser, which can be useful for testing host applications.

cmp.__disable()

returns: void

Example

cmp.__disable(); // CMP won't run even if you try

cmp.__enable()

returns: void

Example

cmp.__enable(); // CMP will work as normal

cmp.__isDisabled()

returns: boolean

Example

cmp.__isDisabled(); // => true/false

Manually

Set a gu-cmp-disabled=true cookie. This is the same as running cmp.__disable().

Example

document.cookie = 'gu-cmp-disabled=true;';

Removing it is the same as running cmp.__enable().

Example

document.cookie = 'gu-cmp-disabled=; Max-Age=0;';

Using Cypress

To disable consent in Cypress tests, see their setCookie documentation.

Development

See the developer docs

版本与发布记录

@guardian/consent-manager 共发布 32 个版本,首次发布于 2026/04/30;过去 12 个月发布了 32 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.3.1latest2026/11/124 天前
0.0.0-canary-20261112084807canary2026/11/124 天前
0.0.0-canary-202611120845102026/11/124 天前
0.0.0-canary-202611120836372026/11/124 天前
0.0.0-canary-202611120828472026/11/124 天前
0.0.0-canary-202611120821002026/11/124 天前

关于 @guardian/consent-manager 的常见问题

@guardian/consent-manager 是什么?

Consent Manager for the Guardian

如何安装 @guardian/consent-manager?

在项目目录运行 npm install @guardian/consent-manager,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:tslib(^2.8.1)、@guardian/ophan-tracker-js(^2.2.10)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@guardian/consent-manager 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@guardian/consent-manager 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@guardian/consent-manager 可以商用吗?

@guardian/consent-manager 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@guardian/consent-manager 的下载量有多少?

根据 npm 官方下载统计,@guardian/consent-manager 在 2026/10/17 – 2026/11/15 这 30 天内被下载 21,254 次,日均约 708 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@guardian/consent-manager 还在维护吗?

最新版本 2.3.1 发布于 2026/11/12(4 天前);至今共发布 32 个版本,其中过去 12 个月发布了 32 个;首次发布于 2026/04/30。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。