UTM-Tracking/Campaign-Tracking with JavaScript Tracking Client

Hello,

How can I set the UTM parameters/tracking parameters for an action in the code using the Javascript Tracking Client (https://developer.matomo.org/api-reference/tracking-javascript)?

Background/thought:

We already use the JS tracking client in an event listener to track various events, e.g.

$matomo.trackEvent(‘UserInteractions’, 'EventA, ‘1234’, 50);

Now I would like to set an mtm_placement BEFORE this event so that the event is assigned to this placement.

But I don’t know how I can do that. I only found the following functions:

_paq.push([‘setCampaignNameKey’, ‘campaign’]);
_paq.push([‘setCampaignKeywordKey’, ‘keyword’]);

Is there an approach or workaround for this? Do I need to do trackLink with the URL parameter for the placement? Or do I have to change the URL with setReferrerUrl and then call trackPageView again? Or appendToTrackingUrl and then a trackPageView? I have to after that

I would be happy about tips and help!

Best regards

Timo

I also tried to append these parameters to the tracking url with this code:

$matomo.appendToTrackingUrl('mtm_source=testsource&mtm_campaign=testcampaign&mtm_placement=12345');
$matomo.trackPageView('Test for Tracking');
$matomo.appendToTrackingUrl('');

But it seems that this also has no effect.

Any ideas how to solve this?

The only way that seems to work is the following:

// Aktuelle URL-Parameter extrahieren
const searchParams = new URLSearchParams(window.location.search);

// Neue Tracking-Parameter hinzufügen
searchParams.append('mtm_source', 'testsource');
searchParams.append('mtm_campaign', 'testcampaign');
searchParams.append('mtm_placement', 'testplacement');

// Neue URL mit Tracking-Parametern erstellen
const newUrl = window.location.pathname + '?' + searchParams.toString();

console.log('newUrl', newUrl);

// Setzen der neuen URL im Matomo Tracking
$matomo.setCustomUrl(newUrl);
$matomo.trackPageView('Test for Tracking');

But is this the right approach? Why is the appendToTrackingUrl not working?

The disadvantage is that all subsequent actions are also assigned to this placement and that shouldn’t actually be the case…

Hi @iparker
I think that if you want to add some UTM param in Matomo trackink via _paq, you should add these params via the page custom URL:

_paq.push(['setCustomUrl', document.location + '?mtm_source=testsource&mtm_campaign=...']);

This is simplified code, you must also check if the page has already some query params, etc.