Content Script tracking with Google Analytics

前端 未结 2 1727
一整个雨季
一整个雨季 2020-12-13 21:22

I am working on a Google Chrome Extension that modifies certain pages with a content script. In order to understand when and where those changes are applied we were looking

2条回答
  •  有刺的猬
    2020-12-13 21:50

    As Eduardo said in his answer you need a background page, so that can be done like that:

    in your manifest.json file:

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

    in content_scripts.js whenever you want to track event, send a message to the background page to trigger that event.

    chrome.runtime.sendMessage({action: "yourEvent"});
    

    background.js

        (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);
        })();
    
        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
    
        // here we receive the coming message from the content script page
        chrome.runtime.onMessage.addListener(function( request, sender, sendResponse ) {
            if(request.action == "yourEvent"){
                _gaq.push(['_trackEvent', "eventCategory", 'eventType']);
            }
        });
    

提交回复
热议问题