【问题标题】:Add Google Analytics to a Chrome Extension将 Google Analytics 添加到 Chrome 扩展程序
【发布时间】:2021-09-21 02:52:32
【问题描述】:

为了将谷歌分析添加到 chrome 扩展,official docs 提供以下 sn-p:

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);

(function() {   var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;   ga.src = 'https://ssl.google-analytics.com/ga.js';   var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();

但是google也推荐to migrate from ga.js to analytics.js

ga.js 是一个遗留库。如果您要开始新的实施, 我们建议您使用此库的最新版本 analytics.js。 对于现有实现,了解如何从 ga.js 迁移到 分析.js。

仔细遵循migration guide 并使用新脚本升级内容安全策略(从https://ssl.google-analytics.com/ga.jshttps://www.google-analytics.com/analytics.js),它根本不起作用,没有显示任何错误消息。

欢迎任何建议,

【问题讨论】:

标签: javascript google-chrome-extension google-analytics


【解决方案1】:

我的解决方案基于官方文档:https://developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference

但稍作修改:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');

// Modifications: 
ga('set', 'checkProtocolTask', null); // Disables file protocol checking.
ga('send', 'pageview', '/popup'); // Set page, avoiding rejection due to chrome-extension protocol 

【讨论】:

  • @locropulenton 你绝对应该接受这个答案。最后两行确实起到了作用(checkProtocolTask 并在发送 pageview 时强制使用页面路径)。
  • 不知何故这对我不起作用。我收到以下错误:Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' https://www.googletagmanager.com". Either the 'unsafe-inline' keyword, a hash ('sha256-xxx'), or a nonce ('nonce-...') is required to enable inline execution. Refused to load the script 'https://www.google-analytics.com/analytics.js' because it violates the following Content Security Policy directive: "script-src 'self' https://www.googletagmanager.com".
  • @lzl124631x 您还需要在清单中配置content_security_policy
【解决方案2】:

这对于那些使用 react 的人来说非常有用: https://github.com/lxieyang/chrome-extension-boilerplate-react

// manifest.json

"content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'"

// AnalyticsProvider.jsx

import { useEffect } from 'react';

export default function AnalyticsProvider() {
  const initAnalytics = () => {
    setTimeout(() => {
      const gaPlugin = _gaq || [];
      gaPlugin.push(['_setAccount', 'XX-XXXXXXXXXX-X']);
      gaPlugin.push(['_trackPageview']);
    }, 2000);
  };

  useEffect(() => {
    (function() {
      var ga = document.createElement('script');
      ga.type = 'text/javascript';
      ga.async = true;
      ga.src = 'https://ssl.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(ga, s);
      initAnalytics();
    })();
  }, []);

  return null;
}

// Popup.jsx(或您选择的任何其他页面)

import AnalyticsProvider from './AnalyticsProvider';

...

return (
    <div className={classes.root}>
    ...
      <AnalyticsProvider />
    ...
    </div>
  );

【讨论】:

  • 请考虑在您的答案中添加一些解释和细节。虽然它可能会回答问题,但仅添加一些代码并不能帮助 OP 或未来的社区成员理解问题或解决方案。
  • 仅供参考,这是在我的控制台中抛出Uncaught ReferenceError: _gaq is not defined。我在const gaPlugin 前面添加了一个var _gaq = _gaq || [];,似乎可以清除它。
【解决方案3】:

您是否确保将分析脚本放入单独的 javascript 文件中?

Google Chrome 扩展程序不会执行内联 JS,请参阅 https://developer.chrome.com/extensions/contentSecurityPolicy#JSExecution

【讨论】:

    【解决方案4】:

    [EDIT] 根据下面的 cmets,此解决方案不适用于 Manifest V3。

    Chrome 扩展文档有一个说明如何执行此操作的教程:developer.chrome.com/docs/extensions/mv3/tut_analytics

    更新您的清单:

    {
      ...,
      "content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'",
      ...
    }
    

    包括 JavaScript,如下所示:

    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
    _gaq.push(['_trackPageview']);
    
    (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = 'https://ssl.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
    

    像往常一样跟踪事件:

    function trackButton(e) {
      _gaq.push(['_trackEvent', e.target.id, 'clicked']);
    };
    

    【讨论】:

    【解决方案5】:

    尝试使用以下 sn-p 进行异步跟踪,这里是 docs

    <script>
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga('create', 'UA-XXXXX-Y', 'auto');
    ga('send', 'pageview');
    </script>
    <script async src='https://www.google-analytics.com/analytics.js'></script>
    

    【讨论】:

      猜你喜欢
      • 2014-10-21
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 2013-07-04
      • 2013-04-14
      • 2021-02-23
      • 1970-01-01
      • 2015-10-06
      相关资源
      最近更新 更多