How to forward events to another dataLayer

Your devs implemented lots of Matomo events but now you've migrated to GTM & dataLayer. Here's how to forward those events.

Justus

Justus

owntag Founder

published March 7, 2022

This is probably a rare problem to have, but it can happen: You may have a lot of events already implemented for one type of data layer, but now you need to switch systems and the name of your data layer array changes.
Note that I am deliberately writing “data layer” to refer to the concept used by all tag managers, not just specificly Google Tag Manager.

While you should still aim to actually change your implementation so that your events are pushed directly to your desired data layer, dev resources are sometimes hard to come by and you have to bridge a gap for a while.

Example:
Your events are pushed to Matomo’s _mtm array, but now you need to push them to Google Tag Manager’s dataLayer array.

With this very simple code, you can forward events from one array to another:

// Imagine this to be your full Matomo code
window._mtm = window._mtm || [];

function proxyDataLayer(sourceDataLayer, targetDataLayer) {
    // Check if there are existing events in target data layer
    if (targetDataLayer.length > 0) {
        // If there are, store them in a variable
        var existingEvents = targetDataLayer;
    }
    targetDataLayer = new Proxy(sourceDataLayer, {});
    // If there are existing events, add them to the new data layer
    if (existingEvents) {
        targetDataLayer.push(...existingEvents);
    }
    return targetDataLayer;
}

// This would be your GTM code
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
    'event': 'gtm.js',
    'gtm.start': new Date().getTime()
});

// This is whery the magic happens
window.dataLayer = proxyDataLayer(window._mtm, window.dataLayer);

// You'll see this in your GTM Preview Mode
// as if it was pushed to dataLayer
window._mtm.push({
    event: "someEvent",
    myVar: "myValue"
});

And voilá - your events are now pushed to GTM’s dataLayer. Meanwhile in Matomo’s _mtm array, the events are still processed by Matomo Tag Manager.

I have only tested this with the combination with GTM and Matomo, but it should work with most other solutions as well.

Become a Server Side Tagging Pro with owntag

Take control of your digital data collection with Server Side Tagging and Server Side GTM – easily hosted with owntag.

App screenshot