简体   繁体   中英

How can I activate Google Tag Manager by inserting it's code in the head via Javascript upon a click?

So my main question is that I have created a website in only HTML, CSS & JavaScript .. no CMS used.

And I added a Cookie Notice from the following website: https://www.cssscript.com/multilingual-cookie-consent-popup/

Now everything works great but it's important that once someone accepts the cookie notice and clicks on "I understand", that only then the Google Tag Manager activation code is added to the HEAD in the HTML document.

But upon loading the website it also needs to check whether a cookie with the name of "cc_cookie" already exists. If the cookie alredy exists then the Google Tag Manager Code should be activated as well and if it doesn't exist then the normal cookie notice should appear.

Does that make sense? Or am I over complicating it?

The main question is: How can I add a cookie notice that activates Google Tag Manager (by inserting the code in the HEAD) upon accepting the cookies using JavaScript?

PS: The GTM activation code is just a script like example code

Thanks in advance for your help!

Maybe you want something like this ?

And replace the gtmId with yours.

function activateGTM(){
    var gtmId = "GTM-AAAAAAA";
    (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer',gtmId);
}

// when user click the cookie button or check the cookie exists
// activateGTM();

creator here the plugin was just updated and now a callback function is fired whenever a user accepts the cookie consent for the first time or if he has alredy accepted it, and also whenever he changes the cookie policy settings. Checkout the github! repository, the demo has also been updated with the callback function has been added as example.

(note: config. settings and demo example on cssscript's website are not up-to date).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM