Salesforce

Client-Side Cookie Management

« Go Back
Information
Client-Side Cookie Management
UUID-518074a1-a6da-81c3-be52-bae7685d9c94
Article Content

Cookie blocking is a crucial step for successful Cookie Consent implementation. When the OneTrust banner is integrated with a website, users can opt-in or opt-out of certain categories of cookies. But without necessary blocking mechanism in place, these choices might not be respected.

To maintain compliance and ensure cookies are fired based on visitor preferences, it is necessary to have appropriate cookie blocking methods implemented when the OneTrust Banner is integrated.

Cookies themselves cannot be directly blocked. However, most cookies that fall under legislation are set through inserted scripts or tags, such as JavaScript or HTML iFrames. This includes most analytics and third-party cookies, such as advertising cookies.

Therefore, to comply with the law, such scripts should be blocked, or substituted for non-cookie alternatives, whenever consent has been withheld or withdrawn.

This article outlines several cookie blocking methods, including custom JavaScript and wrapper control functions, that can be used to control cookies being set on a browser through JavaScript files and in-line scripting.

Note

This article only covers JavaScript. For information on blocking iFrames, see Manually Rewriting iFrames in Cookie Consent.

JavaScript Type Re-Writing

This is the OneTrust recommended method to allow/disallow cookies based on user choices when the cookie script is in the source code. As the name of the method suggests, this method focuses on the type attribute of script tags. This method is the most appropriate when blocking cookie scripts where the HTML script tag has a defined type.

Important

It is recommended that you use this approach whenever possible.

Below are a couple examples in which this method would be applicable.

In-Line Scripting Example:

<script type=’text/javascript’>
document.cookie = “targeting-cookie”+”=”+”1234”
</script>

JavaScript File Example:

<script type=’text/javascript’ src=’/path/cookie.js’></script>

How to Implement

Normal script tags appear as follows:

<script type="text/javascript">
code
</script>

Using script type re-writing, you must change the type attribute’s value and add class to modify the script tag to be implemented only when consent is provided to the relevant category:

<script type="text/plain" class="optanon-category-C0002">
code
</script>

The ID in the class identifier (C0002 above) corresponds to the cookie group ID for the cookies the script loads (in this example, Performance Cookies). For more information on how to find category IDs, see Finding the Cookie Group IDs.

How it Works

The in-line scripting example (above) would appear as follows:

<script type=’text/plain’ class=’optanon-category-C0004’>
document.cookie = “targeting-cookie”+”=”+”1234”
</script>

After re-writing this tag, the script would only fire on the site when a user consents to the C0004 category (Targeting Cookies). The class attribute is responsible for updating the type. When consent is withdrawn/withheld for the assigned category, the type will be text/plain; when consent is given, it will be text/javascript.

In this example, when a user does not consent to Targeting cookies (C0004) , the script tag would appear as follows:

client_side_1_pc.png

When a user consents to Targeting cookies (C0004), the type will appear as follows:

client_side_2_PC.png

Note

You can block multiple categories of cookies using this method with the following syntax:

<script type="text/plain" class="optanon-category-C0002-C0003-C0004">
code
</script>

The values in the phrase class="optanon-category-#-#-#" correspond to the categories of cookies set up in the cookie list for the site. 

When you list multiple categories using this method, the categories are blocked concurrently. None of the cookies in these categories will be set unless the site visitor consents to all of the categories being blocked.

 

The Optanon Wrapper Control

The Optanon Wrapper is provided in the main script tag and appears as follows:

<script type="text/javascript">
function OptanonWrapper() {
}
</script>

It functions as a holder for the helper methods, which are used to block or control any script or HTML tags that cause cookies to be set. The wrapper is executed on each page load, or whenever the user modifies their consent for any cookie categories in the Preference Center.

When cookie groups are switched from Inactive to Active, the relevant helper methods are executed, and the related JavaScript/HTML will be inserted in the page.

The helper method scripts do not have to be placed inside the wrapper control. However, if they are not, they are only executed on first page load. If you want any opt-in action (Inactive to Active) to be reflected immediately in the user experience, then you should use the wrapper.

Changes in the user experience as the result of an opt-out action (Active to Inactive) will only be reflected on page refresh or navigating to a new page.

Below is an example function called through OptanonWrapper():

Example function:

toConsole() {
    console.log(“SUCCESS”)
}
function OptanonWrapper{
  if(OnetrustActiveGroups.includes("C0002")){
    toConsole()
  }
}

OnetrustActiveGroups plays a critical role in the Optanon Wrapper Control method. OnetrustActiveGroups is a data layer variable that gets updated every time a user modifies their choices with the latest category IDs. For more details on this variable, see OnetrustActiveGroups - Using the Data Layer Object.

In the above instance, toConsole() is an example function that is writing a message on the console when the if condition is executed. In this example, the if condition is checking for the OnetrustActiveGroups data layer variable and if it includes the C0002 category, meaning when Performance cookies are active. Whenever this condition is satisfied, the toConsole() function is executed. The toConsole() function will be called every time the OptanonWrapper() fires and when a user consents to Performance cookies (C0002).

When the function is executed based on consent for Performance category, it appears as follows:

client_side_3_pc.png

Note

The toConsole() function written above is strictly an example. Make sure to implement this method if there are any existing functions on the website that are required to be controlled based on consent.

 

SDK-Specific Actions

Third-party tools often have public methods that can be called to indicate to the tool that a user has granted or revoked consent. These will often result in the technology being set to “strict” or “restricted” mode so that a restricted amount of data is processed to respect a user’s choices. If the technology you want to control has these methods, you can implement them through the OptanonWrapper control. See the following example:

function OptanonWrapper(){
	if(OnetrustActiveGroups.includes(“C0002”)){
		myAnalyticsTool.setUnrestrictedMode () //consent given, operate regularly
	}else{
		myAnalyticsTool.setRestrictedMode() //consent not given, operate in restricted mode
	}
}

Events

The OneTrust JavaScript SDK raises several events that can be used to trigger consent-related actions. The two most relevant events are OneTrustGroupsUpdated, which fires when consent becomes available on page load and whenever consent is changed, and OTConsentApplied, which only fires when an explicit consent action has been taken.

window.addEventListener(“OneTrustGroupsUpdated”, event => {
	if(event.details.includes(“C0002”)){
		myAnalyticsTool.setUnrestrictedMode();
}else{
	myAnalyticsTool.setRestrictedMode();
}
})

Note

When using this method, it’s important to ensure that the third-party technology remains uninitialized or is operating in restricted mode until consent becomes available. Otherwise, it’s possible that data collection is occurring for 1-2 seconds before the third party is told to operate in restricted mode.

For more information on OneTrust JavaScript events, see Cookie Consent Java Script Events Guide.

 

Helper Methods

Helper methods are alternative mechanisms that can be used to block or control any script or HTML tags that cause cookies to be set.

Note

Optanon and OneTrust can be used interchangeably. However, we recommend using OneTrust.

OneTrust.InsertScript

With this method, the scripts responsible for setting cookies are placed in an external file, and dynamically inserted in the page when the cookie group they are associated with is Active.

The format is as follows:

OneTrust.InsertScript(url, selector, callback, options, groupId)

Example 1. Example

OneTrust.InsertScript('/gaCookies.js', 'head', null, null, 'C0002');OneTrust.InsertScript('/performance-cookies-script.js', 'head', null, null, '2');
 

In the example below, gaCookies.js is an external file that is setting Google Analytics cookies. This JavaScript file will be inserted only when Performance cookies are active. Implementing this using the InsertScript method within the OptanonWrapper() function would appear as follows:

function OptanonWrapper() { 
            OneTrust.InsertScript('path/gaCookies.js','head', null, null, 'C0002');
 }

The Result:

In this example, the gaCookies.js file will get injected before the closing head tag of the HTML when Performance cookies (C0002) are active. The following script will be inserted in the source and will be executed as a regular JavaScript file:

<script type="text/javascript" src="path/gaCookies.js"></script>
client_side_4_insertscript.png

If the Performance Cookies group (C0002) is Inactive, the script will not be inserted.

Note

Please note that the gaCookies.js used in the scenario above is strictly an example. This method is applicable to any JavaScript file that is required to be injected in the code based on user consent.

See the table below for an explanation of the different parameters.

Parameter

Datatype

Description

Value

Required

url

String

Absolute or relative URL of JS file

 

Yes

selector

String

HTML parent element selector where the script tag will be inserted

head

body

parent id

Yes

callback

Function

A JavaScript function to be called once the script tag has been inserted

function name

null

Yes

options

Object

A list of behaviors for when the script tag is inserted

See Options definition below

Yes

groupId

String

Group ID for which the script tag will be inserted

Optanon Group ID

Yes

 

OneTrust.InsertHTML

This method should be used where the code controlling the setting of cookies is either a standard or custom HTML tag.

The format is as follows:

OneTrust.InsertHtml(element, selector, callback, options, groupId)

Example 2. Example:

OneTrust.InsertHtml('<iframe type="text/html" width="640" height="360" frameborder="no" src="https://www.youtube.com/embed/v=GEH-usLSwqE"></iframe>','123', null, null, 'C0003');OneTrust.InsertHtml('<customElement customAttribute="value">some content</customElement>', 'parent_element_id', null, null, '3');
 

In this example, the iFrame is the standard HTML element to be injected in a section that has ID 123. The first null value specifies that there is not a callback function and the second null value specifies that there is no options parameter added. The group ID (C0003) will allow the element to be inserted when consent is granted for Functional-category cookies.

The Result:

client_side_5_inserthtml.png

Note

Please note that this method will automatically add an enclosing div around the element that is getting inserted.

<customElement customAttribute="value">some content</customElement>

If the Functionality Cookies group is Inactive, the script will not be inserted.

See the table below for an explanation of the different parameters.

Parameter

Datatype

Description

Value

Required

element

String

HTML tag to be inserted

 

Yes

selector

String

HTML parent element id where the element will be inserted

parent ID

Yes

callback

Function

A JavaScript function to be called once the element has been inserted

function name

null

Yes

options

Object

A list of behaviors for when the element is inserted

See Options definition below

null

Yes

groupId

Number

Group ID for which the element will be inserted

Optanon Group ID

Yes

Note

Some third-party components that set cookies use both JavaScript and HTML elements that are interdependent. In most cases, you will then need to use both the HTML and JavaScript helper methods as a pair to avoid any problems of one element being present without the other.

 

The Options Parameter

In both methods above, the options parameter provides a way to further manipulate page content based on whether consent for a group of cookies has been given. This provides a simple mechanism that enables website owners to either incentivize users to opt-in or deliver a different user experience to visitors who opt-out.

The parameter can contain some or all the following:

{
deleteSelectorContent: <bool>,
makeSelectorVisible: <bool>,
makeElementsVisible: [‘<id>’, ‘<id>’, ‘<id>’, ...],
deleteElements: [‘<id>’, ‘<id>’, ‘<id>’, ...]
}

The table below describes the behaviors for each option.

Option

Datatype

Description

Value

Required

deleteSelectorContent

Boolean

Delete all parent container content before inserting the element.

true

false

No

makeSelectorVisible

Boolean

Shows parent container element after inserting the element.

true

false

No

makeElementsVisible

Array

A list of html element id’s to show after inserting the element.

[ID, ID]

No

deleteElements

Array

A list of html element id’s to delete after inserting the element.

[ID, ID]

No

Below are examples for each of these options:

  • deleteSelectorContent

    One of the use-cases for this option is to replace content with script.

    function OptanonWrapper() {
                  let options = { deleteSelectorContent: true
                  }
                 OneTrust.InsertScript('path/gaCookies.js', 'div1', null, options, 'C0003');
                 }

    In the above snippet, OneTrust.InsertScript is utilized to inject gaCookies.js in the parent element with ID div1. Since deleteSelectorContent is set to true, the content of the div1 element will be removed and gaCookies.js will be inserted when a user consents to Functional cookies.

    Results:

    • When functional cookies are inactive:

      delete_selector_content_1.png
    • When functional cookies are active:

      delete_selecor_content_2.png
  • makeSelectorVisible

    This option is applicable when a user has to first consent to a certain category to view the content of an element. To use this option, the prerequisite is for the parent element to be hidden.

    function OptanonWrapper() {
            let options = {
              makeSelectorVisible: true
            }
            OneTrust.InsertScript('path/gaCookies.js', 'div1', null, options, 'C0003');
          }

    In the above example, if the div1 element is hidden initially, then display: block will be added for that element. When Functional cookies are toggled off, the div1 element will not be visible. When a user consents to the Functional category, gaCookies.js will be inserted and the element will become visible since makeSelectorVisible is set to true.

    Results:

    • When functional cookies are inactive:

      make_selector_visible_1.png
    • When functional cookies are active:

      make_selector_visible_2.png
  • makeElementsVisible

    This option is useful when there are multiple elements that are required to be made visible on consent along with script insertion.

    function OptanonWrapper() {
           	let options = {
              		makeElementsVisible: ['div2','div3']
            	}
            	OneTrust.InsertScript('path/gaCookies.js', 'div1', null, options, 'C0003');
          	}

    In the above example, the OneTrust.InsertScript will insert gaCookies.js in the HTML element with ID div1 when a user consents to Functional cookies. Additionally, because the makeElementsVisible parameter is added, the elements in its array (div2 and div3) will be made visible if they were hidden initially.

    Results:

    • When functional cookies are inactive:

      make_elements_visible_1.png
    • When functional cookies are active:

      make_elements_visible_2.png
  • deleteElements

    This is useful in a scenario when multiple elements are required to be deleted once consent is given. Similar to makeElementsVisible, this option is also taken in array as a value.

    function OptanonWrapper() {
            	let options = {
              	deleteElements: ['div2','div3']
            	}
            	OneTrust.InsertScript('path/gaCookies.js', 'div1', null, options, 'C0003');
          	}

    In the above example, when a user consents to Functional cookies, the gaCookies.js will be inserted in div1. Because the deleteElements parameter is added, the div2 and div3 elements will be deleted.

    Results:

    • When functional cookies are inactive:

      delete_elements_1.png
    • When functional cookies are active:

      delete_elements_2.png

Note

  • HTML elements will always be inserted before the closing parent element tag.

  • Setting makeSelectorVisible requires the parent element to be manually hidden initially.

  • All HTML elements specified in the list of ids for makeElementsVisible are required to be manually hidden initially.

  • deleteSelectorContent will delete only the content of the container element.

  • deleteElements will completely delete each element specified.

  • Using the selector to specify some element other than head or body requires the ID value of the parent element.

  • The Options parameter can be used with both the Wrapper Control methods – InsertScript and InsertHtml

 
 
 
 
Article Visibility
161,343
Translation
English
Checked

Powered by