How to enable or disable inline JavaScript based on granted or denied consent
Did you know that you can also load or block external sources based on granted or denied consent? You can learn more in this article.
There are scenarios where you might want to enable or disable inline JavaScript depending on granted or denied consent.
This will require a modification of your JavaScript code (<script></script>
) with regards to the attributes type
and cs-require
.
cs-require
will hold the required consent for an inline script to run.type
will be used to disable the script by default.
Possible values for cs-require
Here are the values that you can use:
neutral
: no specific consent required, but only allowed to run when Consent Studio was loaded.functional
: only when the Functional category is allowed for data processing. This is virtually the same asneutral
when thefunctional
category is required.analytics
: only when the Analytics category is allowed for data processing.marketing
: only when the Marketing category is allowed for data processing.
Step by step guide
Let's say we have the following JavaScript code.
<script type="text/javascript">
// ...
alert('Here is a marketing/tracking cookie!');
// ...
</script>
We want to make sure that it only runs when consent is granted for the Marketing category of data processing.
First off, we will first neutralize the script completely by setting the type from text/javascript
to text/plain
.
<script type="text/plain">
// ...
alert('Here is a marketing/tracking cookie!');
// ...
</script>
Then, we will add the cs-require
attribute and set its value to marketing
.
<script type="text/plain" cs-require="marketing">
// ...
alert('Here is a marketing/tracking cookie!');
// ...
</script>
You have now successfully made sure that this inline script only runs when Marketing consent is granted.
Identifying inline scripts that did not fire
Scripts that are not executed due to insufficient consent will have their class list expanded with the insufficient-consent
class. This is the same behavior as for external sources.