orestbida / cookieconsent

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

Cant make it work in SvelteKit (or even vanillaJS) #588

Closed escapingSamsara closed 6 months ago

escapingSamsara commented 8 months ago

How am I supposed to make this work ?

I was setting up a vite project, importing the css and script from the dist folder, even copied it in a folder of my project, also tried the npm package, imported the button, but nothing happens, I cant even open the modal.

Can someone please explain me how this is supposed to work? Also i want to use this in sveltekit (which also did not work), so if anyone can help me with this i would love to get help !

Update, it works but ONLY when i use the inline script tag in my app.html (SvelteKit), when i want to create and use a cookieconsent-init.js i always get an error or initCookieConsent being undefined.

escapingSamsara commented 8 months ago

made it work (to at least start modifying it) !

I will share how it was possible in case someone else comes about it and struggles implementing it in SvelteKit:

imports needed: ` //src/routes/+page.svelte

`

` //src/route/+layout.svelte

`

i downloaded the files cookieconsent.css (not from dist, but from source, to modify it with my own stylings), and i downloaded cookieconsent.js (also not from dist since i wanted to check out the code)

the npm package vanilla-cookieconsent is not needed at all for it to work (i figure its even better not using it since then you can customize everything easier)

orestbida commented 8 months ago

You can find a SvelteKit example on Stackblitz.

escapingSamsara commented 8 months ago

thanks thats a big help ! (i would suggest adding this link to your docs , since there is no link to the example svelte setup :))

One thing i want to ask is how would i add google analytics, since the gtag script(s) are two scripts, how can i make sure they only trigger when the user accepts the google analytics section ?

orestbida commented 8 months ago

There's already a demo link pointing to the stackblitz examples in the docs. for cookieconsent v3.

I now saw that you were using v2, that's why the link was nowhere to be found.

One thing i want to ask is how would i add google analytics, since the gtag script(s) are two scripts, how can i make sure they only trigger when the user accepts the google analytics section ?

When using a SPA like framework (such as SvelteKit), you need to rely on callbacks/events to handle your scripts.

escapingSamsara commented 8 months ago

Yeah i figured that out already. i dont know why npm installed the 2.9 version.

The question is rather, how the script is correctly implemented since according to google analytics the gtag script (i will post it below) needs to be inserted below the head of the html file. How would one implement it as a callback ?

Also in the docs its said that script should be managed by adding ( type="text/plain" data-category="your-category-name") to enable control if the user actually confirms cookies or not. This doesnt work with the gtag scripts.


<script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'TRACKING_ID');
</script>```

    Since this topic is completely new to me i would highly appreciate your help :)
orestbida commented 8 months ago

There are 3 ways to load/enable scripts:

  1. via script tags
  2. via callback functions
  3. via events

The simplest way is to use script tags; this approach works very well for "traditional" websites that fully reload pages.

On SPA frameworks (React, Vue, Angular ...) injecting scripts is not a good approach, the plugin wouldn't be aware of the scripts tags unless there is a full page load. You have to rely on callbacks/events.

Here is one way to load google analytics when the analytics category is accepted (modified svelte/src/lib/cookieconsent-config.ts)

import { CookieConsentConfig, loadScript, acceptedCategory } from 'vanilla-cookieconsent';

const enableGoogleAnalytics = () => {
    loadScript('https://www.googletagmanager.com/gtag/js?id=TRACKING_ID', {
        async: ''
    });

    window.dataLayer = window.dataLayer || [];
    window.gtag = function(){dataLayer.push(arguments);} // changed function gtag => window.gtag = function
    gtag('js', new Date());
    gtag('config', 'TRACKING_ID');
}

const disableGoogleAnalytics = () => {
    gtag('consent', 'update', {
        'analytics_storage': 'denied',
        'ad_storage': 'denied'
    });
    window['ga-disable-G-TRACKING_ID'] = true;
}

const config: CookieConsentConfig = {
    onConsent: () => {
        if(acceptedCategory('analytics')) {
            enableGoogleAnalytics();
        }
    },

    onChange: ({changedCategories}) => {
        if(changedCategories.includes('analytics')){
            if(acceptedCategory('analytics')){
                enableGoogleAnalytics();
            }else{
                disableGoogleAnalytics();
            }
        }
    },

    // rest of config.
};

export default config;
escapingSamsara commented 8 months ago

thanks for the help ! i implemented it like this and now I am waiting for google analytics to track the page access and therefore see if this works, for now it doesnt seem to be tracking the page , but maybe it needs some time

orestbida commented 8 months ago

Make sure ga cookies are set when the category is accepted. If not, then there's an issue somewhere.

escapingSamsara commented 8 months ago

i checked in dev tools for the cookies, the cc_cookie shows inside cc_cookie.services.analytics array {0: "ga" } as an object, so i guess this means it is set, no ?

I am so sorry for this newb questions but working with cookies is completely new to me as a developer and i just started getting into them

orestbida commented 8 months ago

If you don't see at least 2 cookies starting with ga, then it's not implemented properly.

Capture

Also make sure you don't have an ad-blocker enabled.

escapingSamsara commented 8 months ago

i do see both of them ! , the one with _ga_XXXXXXXX is already showing on load, while the second one being added only after cookies are accepted (analytics/all) is this intended ?

escapingSamsara commented 8 months ago

How can i initialize the cookie consent banner in the root layout so that it opens in every subpage also ? When i use it with the Button component it renders only on the page with the button, when i want to run it without the button component present in the respective file. the banner doesnt get rendered, rather i get rendered a weird empty div below my pages content. the div that gets rendered is the following: cm-wrapper cc--anim

Is this intended or is there another way to implement this in sveltekit (without the need to display the button on each page)

I tried the following in routes/+layout.svelte and routes/+page.svelte : `import config from '$lib/cookieconsent/cookieconsent-config'; import { onMount } from 'svelte'; import { run } from 'vanilla-cookieconsent';

onMount(() => {
    run(config);
});

`
orestbida commented 8 months ago

How can i initialize the cookie consent banner in the root layout so that it opens ...

Doesn't the demo on Stackblitz do exactly what you're asking?

the one with _ga_XXXXXXXX is already showing on load

That shouldn't be the case, unless you've already accepted the analytics category previously.

escapingSamsara commented 8 months ago

How can i initialize the cookie consent banner in the root layout so that it opens ...

Doesn't the demo on Stackblitz do exactly what you're asking?

The stackblitz demo shows a button on every page of the demo (since the modal button component is placed in layout), i managed a work-around that makes it fit nicely in the page, which makes it work :)

stale[bot] commented 7 months ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

dldx commented 1 week ago

For anyone with the same issue as me:

I couldn't get it to work with the node adaptor until I moved the CSS into my static folder and loaded it directly in app.html.

This was the line I added to my app.html:

<link rel="stylesheet" href="%sveltekit.assets%/css/cookieconsent.css" />

And I copied the cookieconsent.css file to /static/css/cookieconsent.css.

There must be some kind of bug in the sveltekit node adaptor which prevents it from including CSS files that are not used by sveltekit components.