Manage consent programmatically
This chapter will teach you how to manage the consents of our cookie widget programmatically.
Where are the consents stored?
The entire proof of user consent is stored in the browser's localStorage (the storage key is named dastra-consents) in json format. The propagation of consents depends on it, that's why it's not recommended to directly modify the data of this key
Access to the consent service
The dastra consent service can be accessed in this way:
<script>
window.dastra = window.dastra || [];
window.dastra.push(['cookieReady',function(manager)
{console.log(manager.consent)}]);
</script>List of methods available in the consent manager
In manager.consent, you have the following methods:
open(): opens the consent widget
close(): closes the consent widget
getAllConsents(): retrieve all consents
hasConsented(): returns
trueif the user has already recorded an explicit consentgetPurposeConsent(purposeLabel:string): get consent for a cookie category
setPurposeConsent(purposeLabel:string, consent:bool): set the consent for a category
getServiceConsent(serviceShortName:string): retrieves consent for a particular service
setServiceConsent(serviceShortName:string, consent:bool): sets the consent for a particular service
Get the list of user's consents (getAllConsents)
Once you access the consent manager, it is very easy to retrieve the consents of the current user:
To call getAllConsents() outside the cookieReady callback (for example from your own code after the widget has loaded), use the full path:
The old top-level syntax dastra.getAllConsents() is no longer supported.
The above method returns a list of all the user's consents
Query consents by category (getPurposeConsent/setPurposeConsent)
Cookie categories are identified by the following string labels:
Necessary
Necessary
Preferences
Preference
Analytics
Analytical
Marketing
Marketing
Other
Other
Unclassified
Unclassified
Always use the string labels (e.g. 'Analytical') — numeric values are not supported by the API.
Handle consents by service
To manipulate consents by service, you will need the simplified service name available in the service management interface of your widget.

Example of use
The following example shows how to apply a full opt-out programmatically — for instance when the user clicks a "Reject all" button you have built yourself, or when honouring a browser privacy signal.
You can equally opt-in selectively — for example to accept analytics only:
Reacting to consent updates (the dastra:consents:updated event)
Every time a user changes their consent choices — through the widget or programmatically via save() — Dastra dispatches a dastra:consents:updated event on window. You can subscribe to it to trigger your own logic: loading third-party scripts, updating the UI, firing an analytics event, etc.
Last updated
Was this helpful?