orestbida / cookieconsent

:cookie: Simple cross-browser cookie-consent plugin written in vanilla js
https://playground.cookieconsent.orestbida.com/
MIT License
3.68k stars 387 forks source link

[Bug]: Scripts with data-category are running before cookies are accepted #699

Closed eduardsv closed 1 week ago

eduardsv commented 1 week ago

Expected Behavior

Scripts that have data-category argument provided should be blocked until user accepts cookie consent message.

Current Behavior

Scripts are running on page load, before user accepts cookie consent message.

Steps to reproduce

I have recreated this issue on StackBlitz

Additional info

When I've tried recreating this issue on CodePen, everything works as expected

Version

3.0.1

On which browser do you see the issue?

Firefox, Chrome, Safari

orestbida commented 1 week ago

The data-category attribute is merely used to assign a category to the script; it does not block the script tag. The only way to block a script tag is by changing the 'type' attribute to a non valid javascript mime type, such as type="text/plain".

Your script tags should look like this instead:

<script type="text/plain" data-category="ads">
    document.getElementById("console-log").innerHTML+= "--- Running ads script ---<br>"
</script>
<script type="text/plain" data-category="analytics">
    document.getElementById("console-log").innerHTML+= "--- Running analytics script ---<br>"
</script>

On Codepen it looks like it's working but it's actually not. Here is the console log of codepen:

Uncaught TypeError: Cannot read properties of null (reading 'innerHTML') 
 at https://cdpn.io/cpe/boomboom/index.html?editors=1011&key=index.html-a0bc11d5-7e23-4633-fa28-055e547dd9ad:32
Uncaught TypeError: Cannot read properties of null (reading 'innerHTML') 
 at https://cdpn.io/cpe/boomboom/index.html?editors=1011&key=index.html-a0bc11d5-7e23-4633-fa28-055e547dd9ad:35
eduardsv commented 1 week ago

I see... It should've been obvious, but I haven't thought about that at all.

Thanks a lot for your help and for a great product!

shibusahu30 commented 4 days ago

how do you unblock these scripts once user gives consent?

orestbida commented 4 days ago

@shibusahu30 they are enabled by the plugin through this function: https://github.com/orestbida/cookieconsent/blob/c4d512f362b49556fd57632acbdc7193eb9b9a12/src/utils/scripts.js#L75