Integrating Cookie Control directly within a sites HTML


For sites that require handling Cookie Control consent preferences directly within the websites HTML, without the use of the default banner, Cookie Control's available public api methods can be used to associate a button's, or similar, onclick function with the changeCategory API method.

This setup allows for Cookie Control to handle required consent management, whilst maintaining full control over the sites structure and styling.

Below are two example setups and guides on how to implement Cookie Control in this manner, utilising an Accept or Reject button, or integrating the consnet management as part of a form.

The examples given are based upon the configuration used by the Department for Work and Pension (DWP) found on the GOV.UK website.

Please note to be compliant with GDPR, if the Cookie Control default banner is hidden completely, a link to the sites cookie management section will need to be included within the site's header or footer, this will allow users to easily access the HTML content created which handles consent management.

Anchor point for Example 1: Accept and Reject Consent Buttons

Anchor point for Creating the HTML content

Within this example we will create a simple HTML section which describes the optional category of Analytics that a user can consent to using an 'Accept' or 'Reject' button.

The HTML can be altered to better suit your site's needs in how best you see fit, what is important is that the Cookie Control configuration for the site mirrors what is presented to the user, describing the different categories offered that a user's has the ability to set their consent preferences for.

  1. 1. Create the html elements, including a header, description and buttons for handling consent of the 'Analytics' category.
  2. <h2>Cookies on [name of service]</h2>
    <h3>Analytics cookies</h3>
    <p>
        Analytics cookies help us to improve our website by collecting and
        reporting information on its usage.
    </p>
    <div class="analytics-button-group">
        <button
            type="button"
            class="analytics-button"
            data-module="analytics-button"
        >
            Accept analytics cookies
        </button>
        <button
            type="button"
            class="analytics-button"
            data-module="analytics-button"
        >
            Reject analytics cookies
        </button>
    </div>
    
  3. 2. Update the 'Accept' and 'Reject' buttons' onclick function to update consent via the Cookie Control changeCategory api method.
  4. <div class="analytics-button-group">
        <button
            type="button"
            class="analytics-button"
            data-module="analytics-button"
            onclick="CookieControl.changeCategory(0, true)"
        >
            Accept analytics cookies
        </button>
        <button
            type="button"
            class="analytics-button"
            data-module="analytics-button"
            onclick="CookieControl.changeCategory(0, false)"
        >
            Reject analytics cookies
        </button>
    </div>
    

The method takes two arguments to alter the consent state of a given optional consent category. Firstly, a number describing it's index within the optionalCookies array and a boolean value for the second argument relating to whether the category is accepted or rejected. If the second argument passed is true, consent is granted, otherwise consent is revoked.

More information on available methods can be found here

Anchor point for Updating the Cookie Control configuration

Now that the custom HTML has been created the Cookie Control configuration will be updated to handle the associated handler functions for the Analytics optional category.

  1. 1. Create the optionalCookies array and create the 'Analytics' category, making sure to match the index within the array, to that of the number parameter passed to the changeCatergory method, in this case it is the first entry with an index of 0
  2. optionalCookies: [
        // first category in array with index of 0
        {
            name : 'analytics',
            label: 'Analytics Cookies',
            description: 'Analytics cookies help us to improve our website by collecting and reporting information on its usage.',
            onAccept : function(){
                console.log('analytics accepted')
            },
            onRevoke: function(){
                console.log('analytics revoked')
            }
        }
    ],
    

The handler functions within this example trigger a simple console.log to showcase that the category is being updated correctly and reflect the consent choice. This can be altered as required, to update the consent state of any additional libraries included.

An example for the final configuration can be found here.

Anchor point for Example 2: Consent Management Form

Anchor point for Creating the HTML content

The following example showcases how consent preferences can be updated through a form instead of an 'Accept' and 'Reject' button.

  1. 1. Create the html elements, including a header and form for handling consent of the 'Analytics' category.
  2. <h1>Cookies on [name of service]</h2>
      <form id="consentForm">
         <fieldset class="input_fieldset disabled" id="input_fieldset_analytics">
            <legend class="legend">Analytics Cookies</legend>
            <div class="radios_items analytic_options">
              <div class="radios_item">
                <input
                  disabled
                  class="radios_input"
                  type="radio"
                  name="analytics"
                  value="true"
                  id="analytics-accept"
                />
                <label class="input_label" for="analytics-accept"> Yes </label>
              </div>
              <div class="radios_item">
                <input
                  disabled
                  class="radios_input"
                  type="radio"
                  name="analytics"
                  value="false"
                  id="analytics-reject"
                />
                <label class="input_label" for="analytics-reject"> No </label>
              </div>
            </div>
          </fieldset>
    
          <button type="submit" class="submit_button">Submit</button>
        </form>
    
    
  3. 2. Update the sites Javascript so that the form's submit button handles the consent update via the Cookie Control changeCategory api method.
  4. 
    // form handler to associate the form with desired consent changes
    document.getElementById("consentForm").addEventListener("submit", function (event) {
    event.preventDefault(); // stop form submitting to a backend
    const analyticsChoice = document.querySelector('input[name="analytics"]:checked')?.value;
    console.log('Submitting form, analytics value:', analyticsChoice);
    // connect with cookie control
    CookieControl.changeCategory(0, analyticsChoice === "true");
    });
    
    

Anchor point for Testing a categories state

Utilising another of the Cookie Control's methods getCategoryConsent it is possible to obtain the current value of the optional category, i.e. whether it is currently accepted or rejected.

This can be done by simply calling the method within your browser's console:

CookieControl.getCategoryConsent(0)

The method accepts a number describing it's index within the optionalCookies array. If the value returned is true, consent is granted, otherwise consent is revoked.

Addtionally it can be used within your configuration's onLoad property, to first test the current value of the category, and then update a related html element to show the state. For this example it will be used to update the checked property of the corresponding input.

const config = {
    // apiKey and other settings...
    onLoad: function () {
        // target form
        const consentForm = document.getElementById('consentForm')
        // use getCategoryConsent method from Cookie Control to determine current value of first category
        const currentAnalyticsConsent =
            CookieControl.getCategoryConsent(0) || false
        // target input with matching value to category
        const matchingAnalyticsInputElement = consentForm.querySelector(
            'div.radios_items.analytic_options input[value=' +
                currentAnalyticsConsent +
                ']'
        )
        // set targetted input checked
        matchingAnalyticsInputElement.setAttribute('checked', true)
    },
}

An example for the final configuration can be found here.