I am building a Chrome Extension with a user interface injected into the pages DOM via a content script.
I have injected the code into a Shadow Root to prevent CSS bleed - and everything is actually starting to come out really nice :-)
BUT I am struggling a bit with Google analytics. I would like to track a mix of different click-events on buttons in the content script (+ on the settings page) to get a better feel of how users are navigating the extension (+ of course page visits).
I struggle with the documentation of message passing to the background script from Google and haven't been able to find some real life examples.
I am unsure how this will work - and what I should actually pass through to the background script in the first place? . Will the content script send a message to background on every click, or will there only be passed an object with info on the event to track from the background script?
I am a bit lost here: My understanding of message-passing between content-script and background like this is rather limited...
I got 2 "work in progress" code snippets so far to work with...
Background Script code so far:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXXX']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = 'https://ssl.google-analytics.com/u/ga_debug.js'; // ----> 'https://ssl.google-analytics.com/ga.js'
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
// here I receive the message from the content script page
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
//track event - create
if(request.action == "analytics_add_item"){
_gaq.push(['_trackEvent',
request.action,
request.item_name.toLowerCase(),
request.item_stat,
request.item_number
]);
}
});
content script:
function trackButtonClick(e) {
console.log('action: "analytics_add_item"', e.target.name);
chrome.runtime.sendMessage({analytics_add_item: e.target.name});
_gaq.push(['_trackEvent', e.target.id, 'clicked']);
}
// let lotsUnitsSlider already defined elsewhere in code (this is a toggle-button)
lotsUnitsSlider.name = lotsUnitsSlider;
lotsUnitsSlider.addEventListener('click', trackButtonClick);
Can anyone help me a bit on my way - thanks :-)