I'm trying to load Google Tag Manager after the user has given consent to do so. I know that there are many options out there, that can do it without having to use Vue, - but they're either chunky, massive and/or pricey. And most of them are ugly too.
In order to implement Google Tag Manager, then a code-snippet has to be added in the <head>
as well as 'first-thing-in-the-body'. And neither of which is inside the famous #app
-vue-instance.
I'm using Vue with WordPress, so I don't/won't have Vue-Router or Vuex. It's an Nginx/Apache-server and the routing is controlled by WordPress.
Here is my code:
import Vue from 'vue';
Vue.mixin( cookieMixins ); // loads getCookie and setCookie
const app = new Vue({
el: '#app',
mixins: [
cookieMixins
],
data: {
cookiesAccepted: false
},
mounted() {
this.cookiesAccepted = ( this.getCookie( 'cookie_consent' ) === 'true' );
this.addGtm();
},
methods: {
acceptCookies() {
this.setCookie( 'cookie_consent', 'true', 30 );
this.cookiesAccepted = true;
this.addGtm();
},
addGtm(){
if( this.cookiesAccepted ){
//
// I want to add the
// Google Tag Manager tags (both the
// snippet for the head and the body here.
//
}
}
},
});
This is an attempt to become GDPR-compliant, - not loading any tracking codes before the user has given it's consent.
Is it true that I need to put this as a JavaScript function outside the Vue-instance? And if so, - how would that look? And can I call it from inside my Vue-instace?
What I've tried
- vue-gtag. Implements the Google Universal Tracking code and not GTM. This is close to what I was hoping for, though.
- vue-gtm. Requires Vue-Router.
- vue-analytics. Same argument as
vue-gtag
, except for Google Analytics and not Google Universal Tracking. - vue-head. Requires Vue-Router.
Extra info
For others using this: you can see the getCookie and setCookie JavaScript functions here.