CookieConsent
The cookie consent component informs users about cookie usage. This banner is shown when they visit a website or an application for the first time.
API
Common properties
These properties are used by the standalone class, the Cookie consent context, and the useCookieConsent hook.
Common texts, groups and cookie data can be found in minimal sitesettings example. The file contains all user interface strings, language options, descriptions for common cookie groups, and details about common Helsinki cookies.
There is also an example hel.fi sitesettings example with all the translations. The file contains all user interface strings, language options, descriptions for common cookie groups, and details about common Helsinki cookies. You can also override parts of it and add your project-specific groups and cookies. Remember to replace the INSERT_YOUR_DOMAIN_NAME_HERE.hel.fi
-strings in the settings file with the domain name of your service.
Options
Property | Required | Description |
---|---|---|
focusTargetSelector | No | Selector for the element that will receive focus once the banner is closed. |
language | No | Falls back to 'en'. |
pageContentSelector | No | Defaults to 'body'. |
settingsPageSelector | No | If this string is set and matching element is found on page, instead of banner, show a full page cookie settings replacing the matched element. Example: '#hds-cookie-consent-full-page'. |
spacerParentSelector | No | Defaults to 'body'. |
submitEvent | No | If set to true , triggers a window level event hds-cookie-consent-changed with detail.acceptedGroups before closing banner. If not set, reloads page instead. Defaults to false , but is always true in React context and hooks. |
targetSelector | No | Defaults to 'body'. |
Site settings
Property | Required | Description |
---|---|---|
cookieName | Yes | Name of cookie where consents are stored to. |
fallbackLanguage | No | Tells which language to use if the requested language is not available. |
groupsWhitelistedForApi | No | Listed groups can be updated by calling the setGroupsStatusToAccepted([]) |
languages | Yes | List of languages. |
monitorInterval | No | Monitoring rate in milliseconds. Must be larger than 50. |
optionalGroups | No | List of optional cookie groups and their descriptions. |
remove | No | Defaults to false . |
robotCookies | No | Listed cookies are not shown to the user but should be allowed to be stored. For example, Siteimprove can set cookies while testing the site. |
requiredGroups | Yes | List of required cookie groups and their descriptions. |
siteName | No | Name of the site to identify where the settings belong. |
Detailed info about properties
Note that the user's consent is required for all types of stored information. Information can be stored to cookies, localStorage, sessionStorage, indexedDB, and cache storage. The word "cookie" is used for all storage types in the settings and in this documentation.
Cookie groups
Property | Description |
---|---|
group[].cookies | List of cookies in this group. |
group[].description | Description of the group in all languages. |
group[].groupId | Unique id for the group. |
group[].title | Title of the group in all languages. |
Cookie information
Property | Description |
---|---|
cookie[].name | Storage name of the item stored in cookies or other storage types. |
cookie[].host | Domain where it is used. |
cookie[].description | Cookie usage description in all used languages. |
cookie[].expiration | Cookie expiration time in all used languages. |
cookie[].storageType | Where the cookie is stored. 1 = cookies, 2 = localStorage, 3 = sessionStorage, 4 = IndexedDB, 5 = Cache Storage. |
Languages
Property | Description |
---|---|
language[].code | Abbreviation of the language, for example en or fi . |
language[].direction | Direction the language is read, for example ltr . |
language[].title | Name of the language, for example English . |
Strings and language
The following strings can be overridden if needed. Note that you also need to provide translations if you override these. It is recommended to use the provided strings.
Property | Description |
---|---|
translations.acceptedAt | Text telling when the consent for a group was given. |
translations.approveAllConsents | Button text for giving consent to all cookies. Shown when settings are closed and the user cannot give optional consents. |
translations.approveOnlyRequiredConsents | Button text for giving consent to only to required cookies. All optional cookie consents are revoked. |
translations.approveRequiredAndSelectedConsents | Button text for giving consent to required cookies and selected cookies. Shown when settings are open. |
translations.bannerAriaLabel | Assistive text for screenreaders about the cookie banner. |
translations.description | Main description. The most common override because this is service-specific. |
translations.formHeading | Heading shown in the details. Seen when settings are opened. |
translations.formText | Description shown in the details. Seen when settings are opened. |
translations.heading | Top level heading. |
translations.hideDetails | Button text for hiding details about a group. |
translations.hideCookieSettings | Text on the show/hide settings -button when settings are shown. |
translations.highlightedGroup | Text shown when a specific group is highlighted and must be accepted. |
translations.highlightedGroupAria | Aria-label for a notification about a group. |
translations.notificationAriaLabel | Aria-label for a notification. |
translations.settingsSaved | Text shown when the settings are saved. |
translations.showCookieSettings | Text on the show/hide settings -button when settings are hidden. |
translations.showDetails | Button text for showing details about a group. |
translations.storageType1 | Translation for "cookie". Seen when settings are opened. |
translations.storageType2 | Translation for "localStorage". Seen when settings are opened. |
translations.storageType3 | Translation for "sessionStorage". Seen when settings are opened. |
translations.storageType4 | Translation for "IndexedDB". Seen when settings are opened. |
translations.storageType5 | Translation for "Cache Storage". Seen when settings are opened. |
translations.tableHeadingsDescription | Title of the “description” column in the cookie description. |
translations.tableHeadingsExpiration | Text of the Period of validity column in the cookie description. |
translations.tableHeadingsHostName | Title of the “hostName” column in the cookie description. |
translations.tableHeadingsName | Title of the “name” column in the cookie description. |
translations.tableHeadingsType | Title of the “expiration” column in the cookie description. |
The consent banner language should be updated to match the language of the page.
Property | Description | Type |
---|---|---|
getAllConsentStatuses | Returns an array of consents in the format of [{group:string, consented:boolean}] . group is the name of the consent group, and consented is true if the user has given consent for it. | () => [{group:string, consented:boolean}] |
getConsentStatus | Returns true if the user has given consents to given group. | (groupName:string) => boolean |
openBanner | Opens the banner on each call and optionally highlights given groups. Use when the user needs to accept a specific group to use specific content. The focusTargetSelector defines the element that will receive focus once the banner is closed. | (highlightedGroups?: string[], focusTargetSelector? :string) => void |
setGroupsStatusToAccepted | Asynchronous function to set specific groups as accepted. Returns true if the groups' status is successfully set to accepted, otherwise false. The given groups must have been listed in siteSettings.groupsWhitelistedForApi . | (acceptedGroupsArray:string[]) => Promise<boolean> |
removeBanner | Removes the banner. | (highlightedGroups?: string[], focusTargetSelector? :string) => void |
removePage | Removes the rendered consents. Returns true if there was a page to remove. | () => boolean |
renderPage | Renders the consents to the element with matching id attribute with the siteSettingsId property. | () => void |
setLanguage | Sets a new language. Render the banner or page again once changed. | () => void |
Saving consents
Consents that the user has given are saved to a city-of-helsinki-cookie-consents
cookie. A version number indicating which version of the component is in use, is stored to a city-of-helsinki-cookie-consents-version
cookie. The version number has no relation to the stored consents.
Cookies are always strings and consents are stored as a JSON-formatted string such as {"cookie-id":"true","another-cookie-id":"false"}
.
The ID of the cookie is stored as cookie.id
. True
means the user has given consent for that cookie. All required cookies are always stored true
, but other sites may list a common cookie optional, so the stored consent is not true
by default.
Callbacks
The React context and hooks have the onChange
callback. The cookie consent class dispatches events that can be listened also without React.
Events
The cookie consent class dispatches three kinds of events:
hds-cookie-consent-ready
is dispatched when the class instance is ready and has loaded settings and consents.hds-cookie-consent-unapproved-item-found
is dispatched when the monitoring system finds an unapproved stored item.hds-cookie-consent-changed
is dispatched if theoptions.submitEvent
is set totrue
and users change their consents. If not set, the Browser page is reloaded instead.
Note: the React context, hooks, and components always set submitEvent
to true
.
Events are dispatched with window.dispatchEvent
and can be listened with window.addEventListener
. Events are dispatched in React and vanilla-js versions.
Properties of the custon window events
Property | Description | Type | Default |
---|---|---|---|
type | The event type. | string | hds-cookie-consent-unapproved-item-found |
detail.storageType | Storage type where the unapproved items were found. | cookie , localStorage , sessionStorage , indexedDB or cacheStorage | - |
detail.keys | Keys of the unapproved items | string | - |
detail.acceptedGroups | Accepted consent groups. | string[] | [] |
Property | Description | Type | Default |
---|---|---|---|
type | The event type. | string | hds-cookie-consent-changed |
detail.acceptedGroups | Accepted consent groups. | string[] | [] |
Property | Description | Type | Default |
---|---|---|---|
type | The event type. | string | hds-cookie-consent-ready |
Properties of the React change events
The hds-cookie-consent-ready
callback is not called with any arguments. Other callback receive the same arguments.
Property | Description | Type | Default |
---|---|---|---|
type | Type of the event. Event types are listed in events. | string | - |
acceptedGroups | Array of accepted group names. | string[] | [] |
storageType | Only in monitor events. Type of storage where the unapproved item was found. | string | - |
storageKeys | Only in monitor events. Keys of the unapproved items. | string[] | - |
CSS variables
The current height of the banner is set to a CSS variable in the html
element.
<html style="--hds-cookie-consent-height: 123px;">
The variable is useful when adjusting the position of elements that could overlay the cookie consent banner. It's removed when the banner is closed.
Using without React
The hds-js
and standalone versions work in any javascript environment.
import { CookieConsentCore } from 'hds-js';const siteSettings = 'url to the settings json or settings as an object';const options = {// options};const instance = await CookieConsentCore.create(siteSettings, options);// the banner opens automatically when needed and options.settingsPageId is not set
Note that the CookieConsentCore.create
is an asynchronous function.
It is recommended to set options.submitEvents
to true
when using the page version. Otherwise the whole page is reloaded after save and the user will not see a notification about successful save and may not notify changes.
The whole page is also reloaded when using the banner without options.submitEvents
, but the banner is closed when the consents are stored and before the page reloads.
When events are used, the changes done by the user should be handled with event listeners.
React context
The recommended way to use cookie consents in React is with the CookieConsentContext
. The context compares stored consents to the site settings and does not render its children until consents are parsed. This is an asyncronous operation and ensures consents are always available to all child components.
import { CookieConsentContextProvider, CookieConsentChangeEvent } from 'hds-react';const onChange = (e: CookieConsentChangeEvent) => {// listen to changes here};const options = {// set options here};const siteSettings = {// set site settings here};<CookieConsentContextProvideronChange={onChange}options={options}siteSettings={siteSettings}></CookieConsentContextProvider>;
Internally, the context uses the useCookieConsents hook and returns the same object the hook returns.
Hooks requiring the React context
Hook | Description | Arguments |
---|---|---|
useCookieContentContext() | Returns the context that internally uses the useCookieConsent hook and returns the same object. | - |
useCookieConsentsInstance() | Returns the cookie consent core instance. | - |
useCookieConsents() | Returns an array of consents in the format of [{group:string, consented:boolean}] . group is the name of the consent group, and consented is true if the user has given consent for it. | - |
useGroupConsent() | Use this hook to query if the user has given consent to a single group. | (group:string) |
useCookieBanner() | Add this hook anywhere the banner should be shown if necessary consents have not been given. Preferably use the CookieBanner component. | - |
useCookieSettingsPage() | Add this hook where the settings page content should be shown. Preferably use the CookieSettingsPage component. | - |
useCookieConsentEvents hook
The cookie consent class dispatches window level events. These can be listened to with window.addEventListener
. The useCookieConsentEvents
hook does this and also handles the removal of the event listeners when the component unmounts. The hook also returns a disposer function to manually remove the event listeners.
Property | Description | Type | Value |
---|---|---|---|
onChange | Required. Called when the consents change. | (e:Event) => void | A change event. |
onReady | Required. Called when the class instance is ready. | () => void | - |
onMonitorEvent | Required. Called when the monitoring system finds an unapproved stored item. | (e:Event) => void | A change event. |
useCookieConsent hook
This hook creates the class instance, listens to events, and renders the parent component when consents or isReady
are changed. The CookieConsentContext
uses this hook, so there is no need to use this hook and the context at the same time. Both can be used, but they share the same class instance.
Other context related hooks and components use this hook and its returned functions automatically. Usually there is no need to use this hook manually.
import { useCookieConsent, CookieConsentChangeEvent } from 'hds-react';const MyComponent = ()=>{const onChange = (e:CookieConsentChangeEvent) => {// listen to changes here};const options = {// set options here};const siteSettings = {// set site settings here};const settingsPageId = 'site-settings;const {isReady } = useCookieConsent({onChange, options, siteSettings, settingsPageId})if(!isReady){return null;}return (<p>Ready</p>)}
The context does not render its children if the returned isReady
property is not true. It is true when settings have been loaded, parsed and compared to the stored consents of the user. This is the safest way to ensure all consents are loaded before components rely on the data.
Property | Description |
---|---|
onChange | See callbacks. |
options | See options. |
siteSettings | See siteSettings. |
settingsPageId | The id of the element where the settings are rendered. |
Property | Description | Type | Default value |
---|---|---|---|
isReady | Indicates are the settings loaded, parsed, and compared to stored consents. | boolean | false |
consents | Given consents. Required consents are always true , even if banner is still open. | Array<{group:string, consented:boolean}> | [] |
instance | Instance of the cookie consent class. | Class instance | null |
openBanner | Opens the banner on each call and optionally highlights given groups. Use when the user needs to accept a specific group to use specific content. The focusTargetSelector defines the element that will receive focus once the banner is closed. | (highlightedGroups?: string[], focusTargetSelector? :string)=>void | - |
openBannerIfNeeded | Opens the banner if all necessary consents have not been given. | ()=>void | - |
renderPage | Renders the consents to the element with matching id attribute with the siteSettingsId property. | ()=>void | - |
removePage | Removes the rendered consents. | ()=>void | - |
settingsPageId | The same value as passed in the settingsPageId property. Used by the useCookieSettingsPage and CookieSettingsPage . | string | hds-cookie-consent-full-page |
language | Current language passed in options. | string | en |
React components
CookieBanner
Renders the banner, but only if the user has not given all necessary consents. Add this component to all pages except where the CookieSettingsPage
is used. This component requires the Cookie Consent context.
CookieSettingsPage
Renders only the contents of the cookie banner, so the same content can be used in the banner and also on a settings page. Do not use the CookieBanner
on the same page or the user might see two places to edit consents. This component requires the Cookie Consent context.