FEATURE: plugins can send more data to Google Tag Manager

This commit is contained in:
Neil Lalonde 2018-01-17 11:18:05 -05:00
parent 6500343431
commit 718e932b44
3 changed files with 38 additions and 11 deletions

View File

@ -1,5 +1,5 @@
import { cleanDOM } from 'discourse/lib/clean-dom';
import { startPageTracking } from 'discourse/lib/page-tracker';
import { startPageTracking, googleTagManagerPageChanged } from 'discourse/lib/page-tracker';
import { viewTrackingRequired } from 'discourse/lib/ajax';
export default {
@ -35,15 +35,7 @@ export default {
// And Google Tag Manager too
if (typeof window.dataLayer !== 'undefined') {
appEvents.on('page:changed', data => {
window.dataLayer.push({
'event': 'virtualPageView',
'page': {
'title': data.title,
'url': data.url
}
});
});
appEvents.on('page:changed', googleTagManagerPageChanged);
}
}
};

View File

@ -38,3 +38,23 @@ export function startPageTracking(router, appEvents) {
});
_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
}
};
_.each(_gtmPageChangedCallbacks, callback => callback(gtmData));
window.dataLayer.push(gtmData);
}

View File

@ -22,9 +22,10 @@ import { registerIconRenderer, replaceIcon } from 'discourse-common/lib/icon-lib
import { addNavItem } from 'discourse/models/nav-item';
import { replaceFormatter } from 'discourse/lib/utilities';
import { modifySelectKit } from "select-kit/mixins/plugin-api";
import { addGTMPageChangedCallback } from 'discourse/lib/page-tracker';
// If you add any methods to the API ensure you bump up this number
const PLUGIN_API_VERSION = '0.8.15';
const PLUGIN_API_VERSION = '0.8.16';
class PluginApi {
constructor(version, container) {
@ -619,6 +620,20 @@ class PluginApi {
modifySelectKit(pluginApiKey) {
return modifySelectKit(pluginApiKey);
}
/**
*
* Registers a function that can inspect and modify the data that
* will be sent to Google Tag Manager when a page changed event is triggered.
*
* Example:
*
* addGTMPageChangedCallback( gtmData => gtmData.locale = I18n.currentLocale() )
*
*/
addGTMPageChangedCallback(fn) {
addGTMPageChangedCallback(fn);
}
}
let _pluginv01;