Skip to content

Commit

Permalink
Update Google Analytics Tracking code to use GA4 properties and gtag …
Browse files Browse the repository at this point in the history
…library (#198)

* Upgrade Google Analytics tracking code to use new GA4 properties and gtag.

* Add missing script tags for gtag to upgrade+error pages.

---------

Co-authored-by: Chris Brewer <[email protected]>
  • Loading branch information
lancehalberd and Chris Brewer authored Jun 3, 2024
1 parent 0b006e9 commit f3ba7bb
Show file tree
Hide file tree
Showing 31 changed files with 93 additions and 69 deletions.
10 changes: 6 additions & 4 deletions prod/error.html
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,13 @@
<a class="button" href="./?fallback=1&amp;ignore=1">Unsupported browsers</a>
</p>
</div>
<script async src="https://www.googletagmanager.com/gtag/js"></script>
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-37048309-' + (location.hostname === 'santatracker.google.com' ? 1 : 2), 'auto');
ga('send', 'pageview');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
window.gtag = gtag;
gtag('js', new Date());
gtag('config', location.hostname === 'santatracker.google.com' ? 'G-NK3LZ78Q1G' : 'G-S9MKN6FWD0');
</script>
<script async src="https://www.google-analytics.com/analytics.js"></script>
</body>
</html>
10 changes: 6 additions & 4 deletions prod/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,14 @@
<link id="favicon" rel="shortcut icon" href="/images/favicon-96.png" sizes="96x96" />

<!-- Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js"></script>
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-37048309-' + (location.hostname === 'santatracker.google.com' ? 1 : 2), 'auto');
ga('set', 'transport', 'beacon');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
window.gtag = gtag;
gtag('js', new Date());
gtag('config', location.hostname === 'santatracker.google.com' ? 'G-NK3LZ78Q1G' : 'G-S9MKN6FWD0');
</script>
<script async src="https://www.google-analytics.com/analytics.js"></script>

<!-- CSS -->
<style>
Expand Down
2 changes: 1 addition & 1 deletion prod/src/firebase.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export function initialize() {
window.firebase = firebase; // side-effect

return remoteConfig.fetchAndActivate().catch((err) => {
ga('send', 'event', 'config', 'failure', 'firebase', {nonInteraction: true});
gtag('event', 'firebase', {action: 'failure'});
console.warn('could not fetch remoteConfig, using defaults', err);
}).then(() => {
return remoteConfig;
Expand Down
10 changes: 6 additions & 4 deletions prod/upgrade.html
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,13 @@
<p msgid="upgrade-warning">Oops! Santa Tracker isn't supported in your browser or you have JavaScript disabled. To access Santa Tracker, download a modern browser or enable JavaScript.<br />For more information visit <a href="https://whatbrowser.org">whatbrowser.org</a></p>
<p><a class="button" href="./?ignore_browser_check=true" msgid="gotovillage">Go to the Village</a></p>
</div>
<script async src="https://www.googletagmanager.com/gtag/js"></script>
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-37048309-' + (location.hostname === 'santatracker.google.com' ? 1 : 2), 'auto');
ga('send', 'pageview');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
window.gtag = gtag;
gtag('js', new Date());
gtag('config', location.hostname === 'santatracker.google.com' ? 'G-NK3LZ78Q1G' : 'G-S9MKN6FWD0');
</script>
<script async src="https://www.google-analytics.com/analytics.js"></script>
</body>
</html>
11 changes: 6 additions & 5 deletions static/entrypoint.js
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ global.subscribe((state) => {
// This happens first, as we modify state as a side-effect.
if (state.status === 'restart') {
state.status = ''; // nb. modifies state as side effect
ga('send', 'event', 'game', 'start', state.route);
gtag('event', 'gameAction', {game: state.route, action: 'start'});
state.control.send({type: 'restart'});
}

Expand Down Expand Up @@ -535,14 +535,15 @@ async function runner(control, route) {
let recentScore = null;

// nb. we also call this as a result of 'restart'
ga('send', 'event', 'game', 'start', route);
gtag('event', 'gameAction', {game: route, action: 'start'});
const analyticsLogEnd = () => {
if (!recentScore) {
return;
}
ga('send', 'event', 'game', 'end', route);
recentScore.score && ga('send', 'event', 'game', 'score', route, recentScore.score);
recentScore.level && ga('send', 'event', 'game', 'level', route, recentScore.level);
// These could probably all be a single event with level+score being optional fields.
gtag('event', 'gameAction', {game: route, action: 'end'});
recentScore.score && gtag('event', 'gameAction', {game: route, action: 'score', extra: recentScore.score});
recentScore.level && gtag('event', 'gameAction', {game: route, action: 'level', extra: recentScore.level});
recentScore = null;
};

Expand Down
2 changes: 1 addition & 1 deletion static/scenes/_shared/js/externs.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ window.santaApp.fire = function(name, ...data) {}
* @param {...?} var_args
* @return {?}
*/
function ga(methodName, var_args) {}
function gtag(methodName, var_args) {}

/**
* @constructor
Expand Down
2 changes: 1 addition & 1 deletion static/scenes/airport/js/controls.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ app.Controls.prototype = {
* @private
*/
updateState_: function(direction) {
window.ga('send', 'event', 'game', 'interact', 'airport');
gtag('event', 'gameAction', {game: 'airport', action: 'interact'});
if (direction > 0) {
this.state.nextState();
} else if (direction < 0) {
Expand Down
4 changes: 2 additions & 2 deletions static/scenes/boatload/js/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ Game.prototype.hitBoat = function(score, time, x, y) {
this.animate_(this.scoreElem, x, y);
this.scoreboard.addScore(score);
this.scoreboard.addTime(time);
window.ga('send', 'event', 'game', 'hit', 'boatload');
gtag('event', 'gameAction', {game: 'boatload', action: 'hit'});
};

/**
Expand All @@ -348,7 +348,7 @@ Game.prototype.missedBoat = function(present, x, y) {
this.lastMissedPresent = present;
present.missed();
window.santaApp.fire('sound-trigger', 'bl_hit_water');
window.ga('send', 'event', 'game', 'miss', 'boatload');
gtag('event', 'gameAction', {game: 'boatload', action: 'miss'});
};

/**
Expand Down
2 changes: 1 addition & 1 deletion static/scenes/commandcentre/js/scene.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ app.Scene.prototype = {
window.santaApp.fire('sound-trigger', 'command_map');
}

window.ga('send', 'event', 'game', 'interact', 'commandcentre');
gtag('event', 'gameAction', {game: 'commandcentre', action: 'interact'});
},

/**
Expand Down
4 changes: 2 additions & 2 deletions static/scenes/demoscene/elements/easteregg-tictactoe.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export class EasterEggTicTacToeElement extends LitElement {

if (!this.cellsAvailable_.length) {
// Draw
window.ga('send', 'event', 'village', 'tic-tac', 'draw', {nonInteraction: true});
window.gtag('event', 'village', {action: 'none', label: 'tic-tac-draw'});
}

this.turn = !this.turn;
Expand All @@ -154,7 +154,7 @@ export class EasterEggTicTacToeElement extends LitElement {
async showWin_(player, w) {
this.isPlaying = false;

window.ga('send', 'event', 'village', 'tic-tac', player, {nonInteraction: true});
window.gtag('event', 'village', {action: 'none', label: 'tic-tac-win', player});

await delay(SHOW_LINE_TIME);
this.winClass = `${player} pos-${w}`;
Expand Down
8 changes: 4 additions & 4 deletions static/scenes/elfmaker/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ share.addEventListener('click', (ev) => {
random.addEventListener('click', (ev) => {
window.santaApp.fire('sound-trigger', 'elfmaker_switch_item');
control.chooseRandom();
window.ga('send', 'event', 'game', 'random', 'elfmaker');
gtag('event', 'gameAction', {game: 'elfmaker', action: 'random'});
});

downloadButton.addEventListener('click', (ev) => {
Expand All @@ -91,7 +91,7 @@ camera.addEventListener('click', (ev) => {
download.setAttribute('href', src);
downloadButton.disabled = false;
});
window.ga('send', 'event', 'game', 'photo', 'elfmaker');
gtag('event', 'gameAction', {game: 'elfmaker', action: 'photo'});
});

photo.addEventListener('hide', (ev) => {
Expand All @@ -100,7 +100,7 @@ photo.addEventListener('hide', (ev) => {
});

download.addEventListener('click', (ev) => {
window.ga('send', 'event', 'game', 'download', 'elfmaker');
gtag('event', 'gameAction', {game: 'elfmaker', action: 'download'});
window.setTimeout(() => {
// dismiss clears href, so delay it
photo.dismiss();
Expand Down Expand Up @@ -207,7 +207,7 @@ api.ready(async (data) => {
};
applyRandomMove((Math.random() < 0.5 ? 'left' : 'right') + 'Wave'); // kicks off random timer
elf.addEventListener('click', (ev) => {
window.ga('send', 'event', 'game', 'poke', 'elfmaker');
gtag('event', 'gameAction', {game: 'elfmaker', action: 'poke'});
applyRandomMove();
});

Expand Down
2 changes: 1 addition & 1 deletion static/scenes/jamband/js/dragdrop.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ app.Draggable.prototype.dragEnd_ = function(x, y) {
this.el.appendTo(droppable);
this.el.trigger('dropped', droppable.data());

window.ga('send', 'event', 'game', 'dropped', 'jamband');
gtag('event', 'gameAction', {game: 'jamband', action: 'dropped'});
} else {
this.el.appendTo(this.container);
this.el.trigger('returned');
Expand Down
8 changes: 4 additions & 4 deletions static/scenes/modvil/elements/maputils.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export async function fetchRoute(url, year = (new Date().getFullYear())) {
destinations = await destinations(fallbackUrl);
} catch (e) {
console.warn('failed to fetch fallback', fallbackUrl, e);
window.ga('send', 'event', 'tracker', 'destinations', 'failure');
window.gtag('event', 'tracker', {action: 'failure', label: 'destinations'});
}
}

Expand Down Expand Up @@ -122,7 +122,7 @@ export class DestinationsCache {
this._listener = listener;

if (this._destinations) {
window.ga('send', 'event', 'tracker', 'destinations', 'cache-hit');
window.gtag('event', 'tracker', {action: 'cache-hit', label: 'destinations'});
this._listener(this._destinations);
}
}
Expand All @@ -146,7 +146,7 @@ export class DestinationsCache {
localStorage['destinations'] = JSON.stringify(destinations);
this._listener(destinations);
this._task = null;
window.ga('send', 'event', 'tracker', 'destinations', 'fetch');
window.gtag('event', 'tracker', {action: 'fetch', label: 'destinations'});
}
return destinations;
});
Expand Down Expand Up @@ -285,7 +285,7 @@ export class DataManager {

if (this._destinations.length > 1) {
// Log this, but only if we have real destination data (not just single Village stop).
window.ga('send', 'event', 'tracker', 'timezone-guess', cands[0].id);
window.gtag('event', 'tracker', {action: 'timezone-guess', label: 'destinations', value: cands[0].id});
console.info('nearest stop (tz):', cands[0].id);
}

Expand Down
6 changes: 3 additions & 3 deletions static/scenes/modvil/elements/modvil-tracker.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ class ModvilTrackerElement extends LitElement {
}

_onMarkerClick(id) {
window.ga('send', 'event', 'tracker', 'click', 'marker');
gtag('event', 'tracker', {action: 'click', label: 'marker'});
if (this.width <= 600) {
return; // ignore click, mobile UI
}
Expand Down Expand Up @@ -330,7 +330,7 @@ class ModvilTrackerElement extends LitElement {
if (!this._duringMapChange && !this._duringResize && this._focusOnSanta) {
this._focusOnSanta = false;
console.warn('removing focus', reason);
window.ga('send', 'event', 'tracker', 'map', reason);
gtag('event', 'tracker', {action: 'unfocusSanta', label: 'map', reason});
}
};
this._map.addListener('center_changed', () => reset('move'));
Expand Down Expand Up @@ -386,7 +386,7 @@ class ModvilTrackerElement extends LitElement {

_onFocusSantaClick() {
this._focusOnSanta = true;
ga('send', 'event', 'tracker', 'click', 'focus-santa');
gtag('event', 'tracker', {action: 'click', label: 'focusSanta'});
}
}

Expand Down
6 changes: 3 additions & 3 deletions static/scenes/modvil/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -296,17 +296,17 @@
};

configureActionButton(document.getElementById('play'), () => {
ga('send', 'event', 'village', 'click', 'play-round');
gtag('event', 'village', {action: 'click', label: 'play-round'});
api.go(playRoute);
});

configureActionButton(document.getElementById('featuredButton'), () => {
ga('send', 'event', 'village', 'click', 'featured');
gtag('event', 'village', {action: 'click', label: 'featured'});
api.go(featuredRoute);
});

configureActionButton(document.getElementById('familyguide'), () => {
ga('send', 'event', 'village', 'click', 'familyguide');
gtag('event', 'village', {action: 'click', label: 'familyguide'});
api.go('familyguide');
});

Expand Down
2 changes: 1 addition & 1 deletion static/scenes/presentbounce/js/world/level.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ app.world.Level = class {
*/
onLevelCompleted() {
if (this.attempt_ === 1) {
window.ga('send', 'event', 'game', 'firsttry', 'presentbounce')
gtag('event', 'gameAction', {game: 'presentbounce', action: 'firsttry'});
}

let score = 0;
Expand Down
2 changes: 1 addition & 1 deletion static/scenes/presentbounce/js/world/spring.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ app.world.Spring = class extends app.world.UserObject {
) {
app.shared.utils.animWithClass(this.$el_, 'animate');
window.santaApp.fire('sound-trigger', 'pb_boing');
window.ga('send', 'event', 'game', 'bounce', 'presentbounce')
gtag('event', 'gameAction', {game: 'presentbounce', action: 'bounce'});
}
}

Expand Down
4 changes: 2 additions & 2 deletions static/scenes/santascanvas/js/canvas.js
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ app.Canvas.prototype.saveToFile = function(e) {
saveCtx.drawImage(this.foregroundBackup, 0, 0, this.saveCanvas.width,
this.saveCanvas.height);

window.ga('send', 'event', 'game', 'save', 'santascanvas');
gtag('event', 'gameAction', {game: 'santascanvas', action: 'save'});

if (this.saveCanvas.msToBlob) { // for IE
var blob = this.saveCanvas.msToBlob();
Expand Down Expand Up @@ -435,7 +435,7 @@ app.Canvas.prototype.saveToFile = function(e) {
app.Canvas.prototype.onTrashClick = function(event) {
this.snow.reset();

window.ga('send', 'event', 'game', 'trash', 'santascanvas');
gtag('event', 'gameAction', {game: 'santascanvas', action: 'trash'});

this.clearAnimation.beginAnimation(this.resetCanvas.bind(this));

Expand Down
2 changes: 1 addition & 1 deletion static/scenes/santasearch/js/character.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ app.Character.prototype.onFound_ = function() {
if (this.isFound) {
return;
}
window.ga('send', 'event', 'game', 'found', 'santasearch')
gtag('event', 'gameAction', {game: 'santasearch', action: 'found'});

window.santaApp.fire('sound-trigger', `ss_character_${this.name}`);
let wasFocused = this.drawerItemElem.hasClass('drawer__item--focused');
Expand Down
2 changes: 1 addition & 1 deletion static/scenes/santasearch/js/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ app.Game.prototype.getRandomHintDistanceOffset_ = function() {
*/
app.Game.prototype.hintLocation_ = function(character) {
window.santaApp.fire('sound-trigger', 'ss_button_hint');
window.ga('send', 'event', 'game', 'hint', 'santasearch')
gtag('event', 'gameAction', {game: 'santasearch', action: 'hint'});

// The location of the character is a top/left percentage of the map
let characterLocation = character.location;
Expand Down
2 changes: 1 addition & 1 deletion static/scenes/snowball/js/snowball/levels/local-level.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export class LocalLevel extends MainLevel {
window.santaApp.fire('game-stop', {
score: population.knockedOut,
});
window.ga('send', 'event', 'game', 'win', 'snowball');
gtag('event', 'gameAction', {game: 'snowball', action: 'win'});
}
}
}
2 changes: 1 addition & 1 deletion static/scenes/speedsketch/js/views/cardsView.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ app.view.CardsView.prototype.showTimesUpCard = function(rounds, callback) {
roundsRecognized));
}

window.ga('send', 'event', 'game', 'recognized', 'speedsketch', roundsRecognized);
gtag('event', 'gameAction', {game: 'speedsketch', action: 'recognized', extra: roundsRecognized});

var modelWidth = 300;
var modelHeight = 225;
Expand Down
2 changes: 1 addition & 1 deletion static/scenes/translations/js/scene.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ app.Scene.prototype.setDefaultLanguages_ = function() {
* @param {string} klangEvent to fire to Klang for Elvish
*/
app.Scene.prototype.playAudio_ = function(string, lang, klangEvent) {
window.ga('send', 'event', 'game', 'listen', 'translations');
gtag('event', 'gameAction', {game: 'translations', action: 'listen'});

if (this.toLang === 'elvish') {
window.santaApp.fire('sound-trigger', klangEvent);
Expand Down
4 changes: 2 additions & 2 deletions static/src/core/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,11 @@ function checkUpgrade() {
// otherwise, reload or complain
console.warn('got out-of-date version, have', siteVersion, 'want', upgradeToVersion);
if (!isProd || localStorage['upgradeToVersion'] === upgradeToVersion) {
ga('send', 'event', 'site', 'upgrade-warn', upgradeToVersion);
gtag('event', 'site', {action: 'upgrade-warn', label: upgradeToVersion});
isOutOfDate = true;
notifyListeners();
} else {
ga('send', 'event', 'site', 'upgrade-attempt', upgradeToVersion);
gtag('event', 'site', {action: 'upgrade-attempt', label: upgradeToVersion});
localStorage['upgradeToVersion'] = upgradeToVersion;
window.location.href = window.location.href;
}
Expand Down
10 changes: 8 additions & 2 deletions static/src/core/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,14 @@ export function buildLoader(loadMethod, fallback=false) {

window.dispatchEvent(new CustomEvent('loader-route', {detail: route}));

ga('set', 'page', `/${route}`);
ga('send', 'pageview');
// We must manually track page views for this application because
// it is a single page application, and automatically tracking all
// url changes will capture query parameter changes that should
// not be tracked as page views.
gtag('event', 'page_view', {
page_title: sceneName,
page_location: `/${route}`
});

const locked = (activeSceneName === null);
loadMethod(url, {route, data, locked}).then((success) => {
Expand Down
Loading

0 comments on commit f3ba7bb

Please sign in to comment.