This repository has been archived on 2023-03-18. You can view files and clone it, but cannot push or open issues or pull requests.
osr-discourse-src/app/assets/javascripts/discourse/lib/page-tracker.js.es6
2019-03-20 14:43:25 +01:00

64 lines
1.4 KiB
JavaScript

let _started = false;
const cache = {};
let transitionCount = 0;
export function setTransient(key, data, count) {
cache[key] = { data, target: transitionCount + count };
}
export function getTransient(key) {
return cache[key];
}
export function startPageTracking(router, appEvents) {
if (_started) {
return;
}
router.on("routeDidChange", () => {
router.send("refreshTitle");
const url = Discourse.getURL(router.get("url"));
// Refreshing the title is debounced, so we need to trigger this in the
// next runloop to have the correct title.
Ember.run.next(() => {
let title = Discourse.get("_docTitle");
appEvents.trigger("page:changed", {
url,
title,
currentRouteName: router.get("currentRouteName")
});
});
transitionCount++;
Object.keys(cache).forEach(k => {
const v = cache[k];
if (v && v.target && v.target < transitionCount) {
delete cache[k];
}
});
});
_started = true;
}
const _gtmPageChangedCallbacks = [];
export function addGTMPageChangedCallback(callback) {
_gtmPageChangedCallbacks.push(callback);
}
export function googleTagManagerPageChanged(data) {
let gtmData = {
event: "virtualPageView",
page: {
title: data.title,
url: data.url
}
};
_gtmPageChangedCallbacks.forEach(callback => callback(gtmData));
window.dataLayer.push(gtmData);
}