javascript - 从 Vue 中添加 Google 跟踪代码管理器(在获得同意后)
问题描述
在用户同意后,我正在尝试加载 Google 跟踪代码管理器。我知道那里有很多选择,无需使用 Vue 就可以做到,但它们要么是厚实的、庞大的和/或昂贵的。他们中的大多数也很丑陋。
为了实现 Google 跟踪代码管理器,必须在<head>
'first-thing-in-the-body' 中添加代码片段。这两者都不是在著名的#app
-vue-instance 中。
我在 WordPress 中使用 Vue,所以我没有/不会有 Vue-Router 或 Vuex。它是一个 Nginx/Apache 服务器,路由由 WordPress 控制。
这是我的代码:
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.
//
}
}
},
});
这是一种符合 GDPR 的尝试, - 在用户同意之前不加载任何跟踪代码。
我是否需要将其作为 JavaScript 函数放在 Vue 实例之外?如果是这样, - 那会怎样?我可以从我的 Vue 实例中调用它吗?
我试过的
- Vue-gtag。实现 Google Universal Tracking 代码而不是 GTM。不过,这接近我所希望的。
- Vue-gtm。需要 Vue 路由器。
- Vue分析。与 的参数相同
vue-gtag
,但 Google Analytics 和 Google Universal Tracking 除外。 - Vue头。需要 Vue 路由器。
额外信息
对于使用它的其他人:您可以在此处查看 getCookie 和 setCookie JavaScript 函数。
解决方案
推荐阅读
- php - 回显字符串然后替换字母的函数
- css - 元素在底部得到了不受欢迎的边距
- docker - 如何为在 K8s 集群外部的同一 localhost 上运行的外部服务创建端点?
- javascript - Material Design Lite 滑块更新
- sql - 在插入Node.js之前插入多个具有递增ID的条目时重复键
- django - 如何将 django 连接到 mqtt 代理?
- php - 我可以覆盖 laravel 5.6 验证吗?
- javascript - 这是表单的代码,涉及输入验证。如何使 JS 代码正常运行?
- python - 如何在将数据推送到 MSSQL 之前删除所有特殊字符
- java - 首次在 Google AppEngine 标准项目上运行 gradle 时出现 NullPointerException