[en] Cookie blocking is a crucial step for successful 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.
[en] 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.
Os cookies em si não podem ser bloqueados diretamente; no entanto, a maioria dos cookies que se enquadram na legislação é definida por meio de scripts ou tags inseridos, como JavaScript ou HTML iFrames. Isso inclui a maioria dos cookies analíticos e de terceiros, como cookies de publicidade.
Portanto, para cumprir a lei, tais scripts devem ser bloqueados, ou substituídos por alternativas não cookies, sempre que o consentimento for retido ou retirado.
Para isso, você pode usar um dos vários métodos de ajuda JavaScript personalizados junto com uma função de controle de wrapper.
Regravação do tipo JavaScript
Este é um dos métodos mais eficientes de impedir que cookies controlados por tags de script
sejam definidos sem consentimento. Este método requer a menor quantidade de alterações em seu local e não requer o uso do invólucro (abaixo).
Importante
É recomendável que você use essa abordagem sempre que possível.
[en] Below are a couple examples in which this method would be applicable.
[en] In-Line Scripting Example:
<script type=’text/javascript’>
document.cookie = “targeting-cookie”+”=”+”1234”
</script>
[en] JavaScript File Example:
<script type=’text/javascript’ src=’/path/cookie.js’></script>
[en] How to Implement
As tags de script normais são semelhantes a estas:
<script type="text/javascript">
code
</script>
Usando a regravação do tipo de script, você precisa alterar os scripts para:
<script type="text/plain" class="optanon-category-C0002">
code
</script>
O número no identificador de classe corresponde ao id do grupo de cookies para os cookies que o script carrega. Nesse caso, são cookies de desempenho.
[en] How it Works
Quando o código acima é carregado, o JavaScript dentro das tags não é executado e nenhum cookies é definido. Em seguida, quando o código de Conformidade de cookies for carregado, se os cookies do grupo associado tiverem consentimento, ele mudará dinamicamente a tag para: script type=text/JavaScript
– o código dentro das tags será reconhecido e executado normalmente.
<script type=’text/plain’ class=’optanon-category-C0004’>
document.cookie = “targeting-cookie”+”=”+”1234”
</script>
[en] 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
.
[en] In this example, when a user does not consent to Targeting cookies (C0004) , the script tag would appear as follows:
[en] When a user consents to Targeting cookies (C0004), the type will appear as follows:
Nota
Você pode bloquear várias categorias de cookies usando esse método com a seguinte sintaxe:
<script type="text/plain" class="optanon-category-C0002-C0003-C0004">
code
</script>
Os valores na frase class="optanon-category-#-#-#"
correspondem às categorias de cookies configuradas na lista de cookies do site.
Quando você lista várias categorias usando esse método, as categorias são bloqueadas simultaneamente. Nenhum dos cookies nessas categorias será definido, a menos que o visitante do site consente com todas as categorias que estão sendo bloqueadas.
O controle Optanon Wrapper
O Optanon Wrapper é fornecido na tag de script principal e tem a seguinte aparência:
<script type="text/javascript">
function OptanonWrapper() {
}
</script>
Ele funciona como um suporte para os métodos auxiliares que são usados para bloquear ou controlar qualquer script ou tags html que fazem com que os cookies sejam definidos. O wrapper é executado em cada carregamento de página ou sempre que o usuário salva as alterações nas configurações de privacidade na Central de preferências.
Quando grupos de cookies são alternados de Inativo para Ativo, os métodos auxiliares relevantes são executados e o JavaScript/HTML relacionado será inserido na página.
Os scripts do método auxiliar não precisam ser colocados dentro do controle do wrapper. No entanto, se não forem, eles serão executados apenas no carregamento da primeira página. Se quiser que qualquer ação de aceitação (Inativo para Ativo) seja refletida imediatamente na experiência do usuário, você deve usar o wrapper.
As alterações na experiência do usuário como resultado de uma ação de cancelamento (ativa para inativa) serão refletidas somente na atualização da página ou na navegação para uma nova página.
[en] Below is an example function called through OptanonWrapper()
:
[en] Example function:
toConsole() {
console.log(“SUCCESS”)
}
function OptanonWrapper{
if(OnetrustActiveGroups.includes("C0002")){
toConsole()
}
}
[en] 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 - usando o objeto Data Layer.
[en] 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).
[en] When the function is executed based on consent for Performance category, it appears as follows:
Nota
[en] 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.
[en] SDK-Specific Actions
[en] 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
}
}
[en] Events
[en] 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();
}
})
Nota
[en] 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.
[en] For more information on OneTrust JavaScript events, see [en] Cookie Consent Java Script Events Guide.
Os métodos auxiliares são usados para bloquear ou controlar qualquer script ou tags html que façam com que os cookies sejam definidos.
Nota
O Optanon e o OneTrust podem ser usados alternadamente. No entanto, recomendamos o uso do OneTrust.
Com esse método, os scripts responsáveis pela configuração de cookies são colocados em um arquivo externo e inseridos dinamicamente na página quando o grupo de cookies ao qual estão associados está Ativo.
O formato é:
OneTrust.InsertScript(url, selector, callback, options, groupId)
Exemplo 1. OneTrust.InsertScript
OneTrust.InsertScript('/gaCookies.js', 'head', null, null, 'C0002');OneTrust.InsertScript('/performance-cookies-script.js', 'head', null, null, '2');
[en] 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');
}
O resultado:
[en] 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>
Se o grupo de Cookies de desempenho com um id de 2 estiver definido como Ativo ou Sempre ativo, o seguinte script será inserido na página imediatamente antes do tag head
de fechamento:
Nota
[en] 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.
Consulte a tabela abaixo para obter uma explicação dos diferentes parâmetros.
Esse método deve ser usado quando o código que controla a configuração de cookies for uma tag HTML padrão ou personalizada.
O formato é:
OneTrust.InsertHtml(element, selector, callback, options, groupId)
Exemplo 2. OneTrust.InsertHTML
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');
[en] 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.
O resultado:
Nota
[en] Please note that this method will automatically add an enclosing div
around the element that is getting inserted.
<customElement customAttribute="value">some content</customElement>
Se o grupo Cookies de funcionalidade estiver Inativo, o script não será inserido.
Consulte a tabela abaixo para obter uma explicação dos diferentes parâmetros.
Nota
Alguns componentes de terceiros que configuram cookies usam elementos JavaScript e HTML que são interdependentes. Na maioria dos casos, você precisará usar os métodos de ajuda em HTML e JavaScript como um par para evitar problemas de um elemento estar presente sem o outro.
Com os dois métodos acima, o parâmetro OPTIONS fornece uma maneira de manipular ainda mais o conteúdo da página com base no consentimento de um grupo de cookies fornecido. Isso fornece um mecanismo simples que permite que os proprietários de sites incentivem a opção de entrar ou oferecer uma experiência de usuário diferente aos visitantes que optarem por não participar.
O parâmetro pode conter alguns ou todos os seguintes itens:
{
deleteSelectorContent: <bool>,
makeSelectorVisible: <bool>,
makeElementsVisible: [‘<id>’, ‘<id>’, ‘<id>’, ...],
deleteElements: [‘<id>’, ‘<id>’, ‘<id>’, ...]
}
A tabela abaixo descreve os comportamentos de cada opção.
[en] Below are examples for each of these options:
-
[en] deleteSelectorContent
[en] 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');
}
[en] 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.
[en] Results:
-
[en] makeSelectorVisible
[en] 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');
}
[en] 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
.
[en] Results:
-
[en] makeElementsVisible
[en] 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');
}
[en] 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.
[en] Results:
-
[en] deleteElements
[en] 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');
}
[en] 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.
[en] Results:
Nota
-
Os elementos HTML sempre serão inseridos antes da marca de elemento principal de fechamento.
-
A configuração makeSelectorVisible requer que o elemento principal seja ocultado manualmente, em princípio.
-
Todos os elementos HTML especificados na lista de ids para makeElementsVisible devem ser ocultados manualmente inicialmente.
-
O deleteSelectorContent excluirá apenas o conteúdo do elemento contêiner.
-
O deleteElements excluirá completamente cada elemento especificado.
-
Usar o seletor para especificar algum elemento diferente de header ou body requer o valor de ID do elemento pai.
-
[en] The Options
parameter can be used with both the Wrapper Control methods – InsertScript and InsertHtml