The JavaScript API of Cookie Consent 4.2.0 consists of the cookieconsent global, the 24 options of run(), the tagged script attributes, the cookies, and the loader. Copy the callback signatures and the DOM events from Free Cookie Consent Callbacks and DOM Events.

The cookieconsent global and its members

Cookie Consent declares one global object, window.cookieconsent, whose members a site uses. Under the TermsFeed loader, cookieconsent is a queueing stand-in until the script file arrives, and only run() works during that time.

Check the arguments and the return value of each member before your code calls it.

Member Arguments Returns Effect
cookieconsent.run(options) The options object The Cookie Consent object, or undefined while it waits for <body> Starts Cookie Consent once per page. A second call keeps the first instance and returns the first object, or undefined while the first one is still starting. The options of the second call are ignored
cookieconsent.openPreferencesCenter() None undefined Opens the Preferences Center. The function exists only once Cookie Consent has started; calling it earlier throws TypeError
cookieconsent.cookieConsentObject None The Cookie Consent object, or undefined before it is built Live reference to the running instance, the way to reach it under the loader
cookieconsent.i18n_enable() Any Nothing Exists only on the loader stand-in. Cookie Consent has no such function, so a queued call throws TypeError in the console once Cookie Consent loads

A page script that declares cookieconsent with let, const, or class stops Cookie Consent from running. A second 4.2.0 copy on the same page does nothing, and the first copy keeps the global, its options, and cookieconsent.openPreferencesCenter().

The object that run() returns, and that cookieconsent.cookieConsentObject holds, carries the members a site reads or calls. Other members are reachable from the console, but they are internal and not part of the API. Check the type column before your code reads a member: userConsentToken holds a string or undefined.

Member Type Effect
cookieConsentObject.openPreferencesCenter() Function, returns undefined Opens the Preferences Center. It works where cookieconsent.openPreferencesCenter() is missing, such as a copy of the script bundled into your own code
cookieConsentObject.isLevelInPurposes(level) Function, returns true or false Tells whether a category is in use, that is, listed in notice_banner_purposes_levels. It returns true for strictly-necessary whether listed or not
cookieConsentObject.log(item, type, log_type) Function, returns undefined Writes item to the console with the label type while debug is on. log_type is 'log', 'info', 'warn', 'error', or 'table'
cookieConsentObject.userConsent.acceptedLevels Object of the 4 categories The current choice, such as {"strictly-necessary": true, "functionality": false, "tracking": true, "targeting": false}. It includes unsaved switch changes while the Preferences Center is open, and a category not in use reads false
cookieConsentObject.userConsent.userAccepted true or false true once the visitor answered
cookieConsentObject.userConsentToken String or undefined The consent token, 12 characters unless user_consent_token sets it. In express mode it stays undefined until the first answer of a visitor without a token cookie; in implied mode it is set on page load
cookieConsentObject.i18n.userLang String The current language code, which the language menu of the Preferences Center changes for the current page

These members show the state inside the browser only. Read the consent state from these members, or from the cookie on your server, with Read the Consent State.

When run() returns and when callbacks run

run() builds Cookie Consent synchronously and returns the object, but every page load callback runs after run() returns. Released inline tagged scripts run inside run(), before cookieconsent.cookieConsentObject is set, in one case only: a visitor who answered, on a page with user_consent_saved_on_page_load off. In every other case they run after run() returns, right after user_consent_saved. Callbacks find the object and cookieconsent.openPreferencesCenter() in place.

A run() called before <body> exists waits for the DOMContentLoaded event. Under the TermsFeed loader, run() runs from a timer once the script file loads, so its return value is lost; read cookieconsent.cookieConsentObject instead.

run() takes one options object, reads it once, and ignores keys it does not know, without a warning. The type of each option names one of these parsing rules.

  1. On/off. The option takes true, false, "true", or "false", in any case and with surrounding spaces ignored. Any other value, such as 1, "yes", or null, means off.
  2. Closed list. A missing, null, or "" value gives the default. Other values are trimmed and lowercased, and an unknown value gives the default and logs Invalid <option> "<value>", using "<default>".
  3. Category list. The option takes an array of category IDs or one ID as a string. Entries are trimmed and lowercased, duplicates are dropped, and unknown entries are left out with a warning. A value that is not an array or a string is ignored with a warning.
  4. URL. Only an absolute http: or https: URL with a hostname is kept, so a relative URL such as /privacy is rejected. A rejected value does not show a link and logs a warning.

The options for consent behavior decide which categories exist, what runs before the visitor answers, and what happens after the answer. Compare each default with your setup: in express mode with page_load_consent_levels not set, every optional tagged script waits until the visitor accepts its category.

Option Type Default Effect
consent_type Closed list: "express", "implied" "express" Express holds the tagged scripts of each optional category until the visitor accepts that category, unless page_load_consent_levels lists it, and shows the "I agree", "I decline", and "Change my preferences" buttons. Implied runs every category in use on page load unless page_load_consent_levels limits them, shows the "OK" and "Change my preferences" buttons, and writes the token cookie on page load when it is missing. Choose a mode with Express and Implied Consent
notice_banner_purposes_levels Category list All 4 categories The categories in use, in the order the consent banner text lists their purposes. An optional category left out has no switch, never runs, and reads false in callbacks. strictly-necessary is always in use, so left out of the list it keeps its locked tab and its scripts still run. An empty list, or one without a known category, gives all 4. Use it with Hide Cookie Categories and Buttons
page_load_consent_levels Category list Not set The categories released on page load while the visitor has not answered. By default it is not set: express then releases only strictly-necessary, and implied mode releases all categories in use. An empty array does not release any optional category in either mode. The TermsFeed generator writes ["strictly-necessary"] for express and all 4 categories for implied
page_refresh_confirmation_buttons On/off false Reloads the page after a click on the "I agree", "I decline", or "Save my preferences" button, so a withdrawn category stops at once. Decide whether you need it with Reload the Page After Consent

These options set the layout, the language, the site texts, the buttons shown, and the element that reopens the Preferences Center. None of them edits the built-in texts: language picks one of the shipped translations, and website_name adds your site name to the Preferences Center. By default, the consent banner shows the "I decline" button and no legal links. Change only the rows your design needs.

Option Type Default Effect
notice_banner_type Closed list: "headline", "simple", "interstitial", "standalone" "headline" The layout of the consent banner. Compare the 4 layouts in Cookie Banner Layouts
palette Closed list: "light", "dark" "light" Adds termsfeed-com---palette-light or termsfeed-com---palette-dark to the consent banner and the Preferences Center. Change the colors with Cookie Banner Colors and Custom CSS
language Language code string Not set A set value alone chooses the language, matched without case and with - or _, and an unsupported value gives English. Without the option, the browser languages choose it, then English. Find the 36 codes in Cookie Banner Languages
website_name Any value, converted to a string and trimmed "" Shown above the Preferences Center title when not blank, as plain text
website_privacy_policy_url URL None The Privacy Policy link in the "More information" tab of the Preferences Center, and in the consent banner text with notice_banner_insert_legal_urls
website_impressum_url URL None The Impressum link in the consent banner text with notice_banner_insert_legal_urls
notice_banner_insert_legal_urls On/off false Adds the Privacy Policy and Impressum links after the consent banner text. Links open in a new tab
notice_banner_reject_button_hide On/off false Hides the "I decline" button in express mode. Keep the button with Reject All Button and Cookie Walls
notice_banner_append Closed list: "afterbegin", "beforeend" "afterbegin" Inserts the consent banner as the first or the last child of <body>. The headline layout then shows at the top or after the footer
open_preferences_center_selector CSS selector string "#open_preferences_center" A click on a matching element, or inside one, opens the Preferences Center and prevents the default action of the click. The selector is checked on every click, so elements added after run() work. An invalid selector logs a warning. An empty value gives the default selector, and every value keeps the listener on. Add a link with Add a Cookie Settings Link
preferences_center_close_button_hide On/off false Hides the close button of the Preferences Center and turns off Escape, so the visitor must save

The storage options set where the 3 cookies apply, how long they last, and which token they carry. Set cookie_domain to share one answer across subdomains, and cookie_duration to keep answers for less than 365 days.

Option Type Default Effect
cookie_domain Domain string, such as "example.com" "" (host-only cookies) The domain= attribute of the 3 cookies, used as written without checks. Use the same value on every subdomain with Share Consent Across Subdomains
cookie_secure On/off false Adds Secure to the 3 cookies
cookie_duration Whole number of days, as a number or a numeric string 365 The lifetime of the 3 cookies, counted from each write. A value that does not parse to a positive number gives 365 and logs a warning, and fractions are cut without a warning ("30.9" is 30). Chrome and Safari shorten long lifetimes; check their limits in Consent Cookie Storage and Duration
user_consent_token String or number None The token stored in cookie_consent_user_consent_token for a visitor with no token cookie yet. A token cookie already in the browser takes precedence over the option. Tie answers to accounts with Keep a Consent Log to Prove Consent

The callback options attach your functions and widen the moments when 2 of the callbacks run. Read the row of each option before your code relies on a callback that runs on every page load.

Option Type Default Effect
callbacks Object mapping callback names to functions or to names of window functions None Your code for the 7 callbacks. Ignored unless it is a non-null object
callbacks_force On/off false scripts_specific_loaded runs for every released category, including categories without tagged scripts and strictly-necessary on every page load. Set it on any page that grants consent signals from scripts_specific_loaded. The other callbacks run without it
user_consent_saved_on_page_load On/off false user_consent_saved runs on every page load of a visitor who answered, with reason 'page_load' and the saved choice, before the accepted categories are released. The Google Consent Mode setup turns it on

Each callback receives its own arguments and runs at its own moment of the consent flow. Look up both, and write the callback functions, with Free Cookie Consent Callbacks and DOM Events.

The diagnostics options help you test a setup. Keep both off on a live site.

Option Type Default Effect
debug On/off false Prints timestamped lines to the console, in the form [<ISO timestamp>][<type>] <message>
demo On/off false Does not write a cookie and shows the consent banner on every page load. Answers still release scripts and run callbacks. Cookies saved earlier are still read

With debug on, Cookie Consent prints a warning for each setup problem it detects and keeps running. The duplicate cookie warning and the error rethrown from a callback appear whether debug is on or off.

Find the line your console shows to learn which setup problem Cookie Consent detected.

Console line Meaning
Invalid <option> "<value>", using "<default>" A closed-list option holds an unknown value
Invalid <option> "<value>", it must be a http(s) URL; the link is not shown A legal URL is relative or not http: or https:
Invalid <option>, it must be an array of cookie levels; the option is ignored A category list option is not an array or a string
Invalid cookie level "<entry>" in <option>, it is left out A category list option holds an unknown category
Invalid cookie_duration "<value>", using 365 days cookie_duration does not parse to a positive number
Invalid cookie-consent tag level for JavaScript script: <value> A tagged script has an empty or unknown data-cookie-consent value and never runs
JavaScript script of the category "<category>" never runs: the category is not in notice_banner_purposes_levels A tagged script belongs to a category not in use
Invalid open_preferences_center_selector, no element will open the Preferences Center: <selector> The selector is not valid CSS
[Cookie Consent] <cookie name> is set more than once, probably by subdomains with different cookie_domain settings; use the same cookie_domain on every subdomain Copies of a cookie exist for several domains, usually because subdomains set different cookie_domain values. Printed with console.warn, without the timestamp
The consent levels cookie is missing or invalid, the Notice Banner is shown again cookie_consent_user_accepted exists without a valid cookie_consent_level cookie, so Cookie Consent removes cookie_consent_user_accepted and shows the consent banner until the visitor answers again
run() was already called on this page, ... A second run() call was ignored
window.cookieconsent does not exist, cookieconsent.openPreferencesCenter() is not available; use cookieConsentObject.openPreferencesCenter() Cookie Consent was bundled or wrapped instead of loaded with a <script> tag
Error while trying to enable a JavaScript script: <message> A tagged script failed to release; the next one runs
Error in Customer Callback <name>: <error> A callback threw an error; the consent flow continues, and the error itself is rethrown to the console

A tagged script is a classic <script> element with type="text/plain" and a data-cookie-consent attribute, which Cookie Consent releases when its category is accepted. Cookie Consent reads tagged scripts once, when run() starts, so a tagged script added later never runs.

Write each attribute on a tagged script with an allowed value, and check which attributes Cookie Consent adds or keeps on the released copy.

Attribute Value Effect
type text/plain Keeps the browser from running the script. The released copy carries type="text/javascript"
data-cookie-consent strictly-necessary, functionality, tracking, or targeting, case-sensitive The category that releases the script. An empty or unknown value logs a warning and the script never runs. A text/plain script without the attribute is ignored silently
src Any script URL Supported. The released copy loads the same URL
async Present or absent Kept. An external script without async holds the rest of its category until it loads, fails, or 10 seconds pass
nonce, data-nonce The page nonce Gives the released copy its nonce under a Content Security Policy. Neither attribute is copied as such, and the page nonce is never lent to a tagged script without one
defer, id, integrity, crossorigin, onload, data-*, and any other attribute As written Kept on the released copy
initial-data-cookie-consent The category Added by Cookie Consent to the released copy, which marks it in the Elements panel

Released scripts run in page order within their category and are appended to the end of <head>. Categories never wait for each other. A type="module" script you tag with type="text/plain" is held, then runs as a classic script, where import and export fail. Cookie Consent does not hold iframes, images, or pixels. Tag your scripts step by step with Block Scripts Until Consent.

Cookie Consent writes 3 first-party cookies and uses no localStorage or sessionStorage.

Read the consent state from each cookie in the format it holds.

Cookie Holds
cookie_consent_level The 4 categories as URL-encoded JSON, such as {"strictly-necessary":true,"functionality":false,"tracking":true,"targeting":false}
cookie_consent_user_accepted true once the visitor answered
cookie_consent_user_consent_token The consent token, 12 characters unless user_consent_token sets it

All 3 cookies carry path=/ and SameSite=Strict, and none carries HttpOnly. Check the attributes of each cookie, and when Cookie Consent writes it, in the 3 cookies Cookie Consent writes.

The address the TermsFeed generator writes, https://www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js, is a small loader that fetches the script itself. The loader holds your run() call, passes the nonce of its own <script> tag to the 2 files, and loads them.

  1. The loader stops when the page already has Cookie Consent or a stand-in from another loader, and then does not set a stand-in or request a file.
  2. The loader sets a stand-in: window.cookieconsent becomes an object whose run() queues each call until the script arrives.
  3. The loader takes the nonce from its own <script> tag, or falls back to the nonce on another script whose address starts with the TermsFeed host.
  4. The loader appends 2 async scripts to <head>, both with that nonce. The first is the script itself, https://www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent-code.js. The second is a ping.
  5. The loader replays the queued calls once the script file loads, and each queued run() call runs in its own timer.

The ping returns an empty script and carries the page hostname and no consent data. The script file does not make any further request once it runs.

The loader does not add a charset attribute to the script it injects. The www.termsfeed.com host serves both files with Content-Type: application/javascript; charset=utf-8, so the page encoding does not change the texts in the hosted script. Declare UTF-8 with <meta charset="UTF-8"> anyway, for your own text and for a self-hosted copy. Check why TermsFeed does not recommend a self-hosted copy in Self-Host Free Cookie Consent on Your Server.