Browser runtime methods
Every property and method of window.PiedapConsent and of the npm controller, with parameters, return values, errors and examples.
The script tag creates one global, window.PiedapConsent. Its properties and methods are listed here, with the consent snapshot they return.
Requirements#
- Runtime version 1.0.7, loaded with a publishable key.
- For methods that change the choice: a form that applies to the visitor. Call them after
ready.
Install#
Load the runtime with the script tag or the npm package. See Browser runtime options.
Get the API object#
window.PiedapConsent
window.piedapConsent // the same objectThe global exists as soon as the script tag has run. With the npm package, createConsent() returns a controller with the same methods. See npm controller differences.
piedapConsentQueue.push()#
Runs a callback once the runtime is ready, for code that may run before the script tag.
| Parameter | Type | Required or default | Description |
|---|---|---|---|
callback |
(api) => void |
Required | Called with the API object. |
Returns nothing.
Errors None. A value that is not a function is ignored.
<script>
(window.piedapConsentQueue = window.piedapConsentQueue || [])
.push(function (consent) {
if (consent.hasConsent('analytics')) {
console.log('analytics allowed');
}
});
</script>Properties#
| Property | Type | Description |
|---|---|---|
version |
string |
The runtime version, such as "1.0.7". |
ready |
Promise<ConsentSnapshot> |
Resolves once the runtime knows which form applies and what this browser already answered. It also resolves when the API cannot be reached. It never rejects. |
consentId |
string | null |
The record's id. null until the API has stored a first answer. |
decisions |
{ purposeKey, granted, partners? }[] |
The choice in the format the API takes. partners appears only on an allowed purpose with some partners switched off. |
globalPrivacyControl |
boolean |
The browser sends a Global Privacy Control signal. |
metadata |
Record<string, unknown> |
The fields set with setMetadata(). |
identifiers |
{ subjectType, subjectId }[] |
The identifiers set with setIdentifiers(), without their proofs. |
PiedapConsent.ready.then((consent) => {
console.log(consent.law, consent.consentModel, consent.decided);
});Methods#
getConsent()#
Returns the current state.
Takes no parameters.
Returns a consent snapshot.
Errors None.
const consent = PiedapConsent.getConsent();hasConsent()#
Tells whether a purpose, a category or one partner is allowed right now.
| Parameter | Type | Required or default | Description |
|---|---|---|---|
target |
string |
Required | A purpose key, or a category name in any case. A purpose key wins when both match. |
partnerKey |
string |
None | One partner of the purpose. target must then be a purpose key. |
Returns boolean. Before ready, it answers from the choice stored in this browser, and false when there is none.
Errors None. An unknown key returns false.
PiedapConsent.hasConsent('analytics'); // a purpose
PiedapConsent.hasConsent('MARKETING'); // a category
PiedapConsent.hasConsent('analytics', 'matomo'); // one partnerWhere no form applies to the visitor's region, every category is allowed and purpose keys are unknown. Check a category there. granted(target) is an older name for hasConsent(target) and still works.
partnerAllowed()#
Tells whether one partner of a purpose may run.
| Parameter | Type | Required or default | Description |
|---|---|---|---|
purposeKey |
string |
Required | The purpose. |
partnerKey |
string |
Required | The partner's key. |
Returns boolean: true when the purpose is allowed and the visitor did not switch that partner off.
Errors None. A partner key the purpose does not list returns false.
if (PiedapConsent.partnerAllowed('analytics', 'matomo')) {
console.log('Matomo may run');
}whenGranted()#
Waits until a purpose, a category or one partner is allowed.
| Parameter | Type | Required or default | Description |
|---|---|---|---|
target |
string |
Required | A purpose key or a category name. |
partnerKey |
string |
None | One partner of the purpose. |
Returns Promise<void>. It resolves at once when hasConsent(target, partnerKey) is already true, otherwise when the visitor allows it.
Errors None. The promise never rejects, and it does not resolve if the visitor never allows the target.
PiedapConsent.whenGranted('marketing').then(() => {
const pixel = document.createElement('script');
pixel.src = 'https://ads.example.com/pixel.js';
document.head.appendChild(pixel);
});setConsent()#
Sets purposes from your own interface and records the answer as the banner would.
| Parameter | Type | Required or default | Description |
|---|---|---|---|
answers |
Record<string, boolean> |
Required | Purpose key to allowed. A purpose you leave out keeps its answer. |
partners |
Record<string, Record<string, boolean>> |
None | Purpose key to partner key to allowed. A purpose you leave out keeps its partner answers. |
Returns nothing. The record's interaction is SAVE_PREFERENCES for a first answer and PREFERENCE_CENTRE for a change.
Errors None. Purposes that are always on stay on, and a partner key the purpose does not list is ignored.
PiedapConsent.setConsent({ analytics: true, marketing: false });
PiedapConsent.setConsent(
{ analytics: true },
{ analytics: { matomo: false } },
);acceptAll()#
Allows every purpose and every partner, and records the answer.
Takes no parameters.
Returns nothing.
Errors None.
PiedapConsent.acceptAll();rejectAll()#
Refuses every optional purpose and every partner with it, and records the answer.
Takes no parameters.
Returns nothing.
Errors None. Purposes that are always on stay on.
document.getElementById('reject')
.addEventListener('click', () => PiedapConsent.rejectAll());allowCategory()#
Allows every purpose in one category and keeps all other answers.
| Parameter | Type | Required or default | Description |
|---|---|---|---|
category |
string |
Required | FUNCTIONAL, ANALYTICS, MARKETING, PERSONALISATION, SALE_OR_SHARING or SENSITIVE, in upper case. |
Returns nothing.
Errors None. Call it only for a category your form asks about.
PiedapConsent.allowCategory('MARKETING');withdraw()#
Refuses everything optional at once and marks the record as withdrawn, with the date.
| Parameter | Type | Required or default | Description |
|---|---|---|---|
reason |
string |
None | Stored on the withdrawal. A longer reason is cut to 500 characters, with a console warning. |
Returns Promise<void>. It resolves once the API has the withdrawal, or once the withdrawal is queued because the API cannot be reached. A queued withdrawal is sent on a later page load. The banner closes and is not shown again.
Errors The promise rejects with the API's error when the API refuses the withdrawal, such as for a record that was erased, and the error event fires. The browser stays withdrawn either way.
The runtime sends one call, POST /sdk/v1/consent/{consentId}/withdraw. On a first visit, with no record yet, it records the refusal and then withdraws it. An answer still on its way is recorded first, and that record is the one withdrawn.
try {
await PiedapConsent.withdraw('Withdrawn from the account page');
} catch (error) {
console.warn('Withdrawal refused', error.code);
}reset()#
Forgets what this browser stored and starts again, which shows the banner.
Takes no parameters.
Returns Promise<ConsentSnapshot>. The local storage entry and both consent cookies are removed, and the browser gets a new random id.
Errors None. The record already on the API is not changed. Meant for testing.
await PiedapConsent.reset();show()#
Shows the first layer, also when the visitor has already answered.
Takes no parameters.
Returns nothing.
Errors None. Nothing is shown where no form applies.
PiedapConsent.show();showPreferences()#
Opens the preferences dialog.
Takes no parameters.
Returns nothing.
Errors None.
document.getElementById('cookie-settings')
.addEventListener('click', () => PiedapConsent.showPreferences());showDoNotSell()#
Opens the opt-out dialog, which lists the marketing, sale-or-sharing and personalisation purposes.
Takes no parameters.
Returns nothing.
Errors None.
PiedapConsent.showDoNotSell();hide()#
Closes the banner and any dialog without recording anything.
Takes no parameters.
Returns nothing.
Errors None.
PiedapConsent.hide();setMetadata()#
Replaces your own fields, which go with the next answer the visitor gives.
| Parameter | Type | Required or default | Description |
|---|---|---|---|
values |
Record<string, unknown> | null |
Required | The fields. null clears them. |
Returns boolean: true when the fields were set.
Errors Returns false and changes nothing when the value is not JSON or is larger than 6,144 bytes.
PiedapConsent.setMetadata({ customerTier: 'gold', storeRegion: 'south-india' });The runtime sets the fields sdk and layer itself. Metadata is returned only to calls made with a secret key.
setIdentifiers()#
Replaces the further identifiers each record this page writes can be found by.
| Parameter | Type | Required or default | Description |
|---|---|---|---|
identifiers |
LinkedIdentifier[] | null |
Required | Up to five entries of { subjectType, subjectId, proof? }. null clears them. |
Returns boolean: false only when the value is neither an array nor null.
Errors None thrown. An entry is left out, with a console warning, when its type is unknown, its subjectId is not 1 to 255 characters, or it needs a proof and has none. If the API refuses a proof, the answer is recorded without identifiers.
const phoneProof = document.body.dataset.phoneProof;
PiedapConsent.setIdentifiers([
{ subjectType: 'SESSION_ID', subjectId: 'sess_4Hq9x2' },
{ subjectType: 'PHONE', subjectId: '+919800000001', proof: phoneProof },
]);COOKIE_ID and SESSION_ID need no proof. EMAIL, PHONE, USER_ID and DEVICE_ID need an identity proof from your server. Identifiers are kept in memory only, so set them on each page load. See Identifiers.
on()#
Adds an event listener and returns a function that removes it. See Browser runtime events.
The consent snapshot#
getConsent(), ready, every listener and the piedap:consent event give the same object.
| Field | Type | Description |
|---|---|---|
ready |
boolean |
The runtime has finished starting. |
consentId |
string | null |
The record's id. null until the API has stored a first answer. |
formId |
string | null |
The form shown to this visitor. null where no form applies. |
formKey |
string | null |
That form's key. |
formVersion |
number | null |
That form's version. |
consentModel |
'OPT_IN' | 'OPT_OUT' | 'NOTICE_ONLY' | null |
How the visitor's region asks. |
law |
string | null |
The law code of the region rule, such as DPDP, GDPR or CCPA_CPRA. |
purposes |
Record<string, boolean> |
Purpose key to allowed. |
partners |
Record<string, Record<string, boolean>> |
Purpose key to partner key to allowed, for every purpose that names partners. |
categories |
Record<PurposeCategory, boolean> |
Category to allowed. |
decided |
boolean |
The visitor has made a choice for this form, or none is needed. |
decidedAt |
string | null |
When, as an ISO 8601 time. |
interaction |
string | null |
How the choice was made in this page view. null when the answer was read back from the API. |
globalPrivacyControl |
boolean |
The browser sends a Global Privacy Control signal. |
pendingSync |
boolean |
A choice is saved in this browser but has not reached the API yet. |
eighteenOrOver |
boolean | null |
The visitor's answer to "Are you 18 or older?". null until the form asks and the visitor answers. |
interaction is one of ACCEPT_ALL, REJECT_ALL, SAVE_PREFERENCES, PREFERENCE_CENTRE, DISMISS, DO_NOT_SELL, GPC_SIGNAL and WITHDRAW. Before the visitor answers, purposes holds the defaults of the region: everything optional is false under OPT_IN.
When eighteenOrOver is false, only purposes that are always on or covered by a Fourth Schedule entry can be allowed. setConsent(), acceptAll() and allowCategory() leave every other purpose refused. See DPDP duties for rights and children.
{
"ready": true,
"consentId": "cns_3f9a1c0e5b7d4a2c9e8f6b1d0a7c5e42",
"formId": "0b6f0f5e-6a0f-4c1e-9d2b-5a4d7a1e9c33",
"formKey": "cookie-banner",
"formVersion": 3,
"consentModel": "OPT_IN",
"law": "DPDP",
"purposes": { "essential": true, "analytics": true, "marketing": false },
"partners": { "analytics": { "google-analytics": true, "matomo": false } },
"categories": {
"STRICTLY_NECESSARY": true,
"FUNCTIONAL": false,
"ANALYTICS": true,
"MARKETING": false,
"PERSONALISATION": false,
"SALE_OR_SHARING": false,
"SENSITIVE": false
},
"decided": true,
"decidedAt": "2026-09-28T06:41:12.345Z",
"interaction": "SAVE_PREFERENCES",
"globalPrivacyControl": false,
"pendingSync": false,
"eighteenOrOver": null
}Categories#
| Category | Allowed when |
|---|---|
STRICTLY_NECESSARY |
Always. |
FUNCTIONAL, ANALYTICS, MARKETING, PERSONALISATION, SALE_OR_SHARING, SENSITIVE |
The form has a purpose in the category, and every purpose in it that is not always on is allowed. |
Where no form applies to the visitor's region, every category is allowed.
npm controller differences#
createConsent() returns a ConsentController. It has every method above. These differ:
| Global | npm controller |
|---|---|
consentId |
consent.getConsent().consentId |
globalPrivacyControl |
consent.getConsent().globalPrivacyControl |
metadata |
consent.getMetadata() |
identifiers |
consent.getIdentifiers() |
decisions |
Build it from consent.getConsent().purposes. |
| Not on the global | consent.init() starts the runtime when you passed autoInit: false. |
| Not on the global | consent.prime() runs the first part of start-up at once: Consent Mode defaults, the stored choice and automatic blocking. init() calls it. |
| Not on the global | consent.setLocale(locale) redraws an open banner in another language the form is published in. |
The package also exports SDK_VERSION, gcmState, partnerKeyFromName, partnerKeys and the cookie parsers. It exports the decision functions the runtime uses as well: acceptAll, rejectAll, defaultDecisions, categoriesFor and normalisePartners. Its TypeScript types include ConsentSnapshot, ConsentOptions, ConsentEventName, ConsentModel, PurposeCategory, SubjectType and LinkedIdentifier.