从第三方脚本访问全局函数

Access global function from a third party script

我正在尝试安装声明全局函数并在某些页面中访问它的脚本。

该脚本是来自 Google 跟踪代码管理器 (GTM) 的 "conversion tracking tag"。它非常简单,与许多第三方脚本(用于分析或其他)非常相似。

GTM's documentation 要求设置 3 个脚本:

1) header

中的脚本
<!-- Global site tag (gtag.js) - Google Ads: 123456789 -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-123456789">

2) 初始化脚本

<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'AW-123456789');
</script>

3) 页面脚本

<!-- Event snippet for Example conversion page -->
<script>
  gtag('event', 'conversion', {'send_to': 'AW-123456789/AbC-D_efG-h12_34-567',
    'value': 1.0,
    'currency': 'USD'
  });
</script>

我的尝试

1) header

中的脚本

这是非常有据可查且简单明了的。我已经编辑了 nuxt.config.js 文件:

//nuxt.config.js

module.exports = {
  head: {
    //...
    link: [
      //...
      {
        src: "https://www.googletagmanager.com/gtag/js?id=AW-123456789",
        async: true
      }
    ]
  }
}

看起来不错,我可以在网络连接中看到请求。

2) 初始化脚本

我创建了一个简单的 Nuxt 插件:

// plugins/gtag.js

/* eslint-disable */
window.dataLayer = window.dataLayer || [];
function gtag() {
  dataLayer.push(arguments);
}
gtag("js", new Date());
gtag("config", "AW-123456789");

并在浏览器中加载它:

//nuxt.config.js

module.exports = {
  plugins: [
    //...
    { src: "@/plugins/gtag", ssr: false }
  ],
}

3) 页面脚本

这是我遇到麻烦的部分。

我想从某些页面访问插件中声明的 gtag() 函数。

所以我在一个方法中调用脚本:

methods: {
  open() {
    gtag('event', 'conversion', {'send_to': 'AW-123456789/AbC-D_efG-h12_34-567',
      'value': 1.0,
      'currency': 'USD'
    });
  }
}

我收到错误:

ReferenceError: gtag is not defined

我错过了什么?

您只在插件范围内定义了函数。

你想要做的是将你的函数注入到Vue实例和SSR上下文中(docs):

// plugins/gtag.js

/* eslint-disable */
window.dataLayer = window.dataLayer || [];
const gtag = function() {
  dataLayer.push(arguments);
}
gtag("js", new Date());
gtag("config", "AW-123456789");

module.exports = ({ app }, inject) => {
  inject('gtag', gtag)
}

像这样使用它(注意函数前面的强制性 $ 符号):

methods: {
  open() {
    this.$gtag('event', 'conversion', {'send_to': 'AW-123456789/AbC-D_efG-h12_34-567',
      'value': 1.0,
      'currency': 'USD'
    });
  }
}