First of all I am new to Google Tag Manager so apologies for my explanation.
I am trying to implement a Google Tag Manager to my website. I am not trying to use too many features but the main thing I am trying to do is load my website with a query string parameter:
Example: (key & value: www.myweb.com?key=key&value=value)
which then I am trying to create a function that pushes the key and value to the Google Tag Manager Data Layer
I have added the following code:
$(document).ready(function (){
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
console.log(params)
window.dataLayer = window.dataLayer || [];
dataLayer.push({params.key:params.value})
//window.dataLayer.push({"Event":"dog"})
})
I have an index.html and have added the head script and body script from google tag manager (the page is hosted online with Google Firebase). I am not sure how to send the key value to Google Tag Manager Data Layer but the main thing is when I do send it, where do I find this information on Google Tag Manager, do I need to create a variable or something on GLM ?
Thank you in advance.
Please do let me know if you require anymore information
This is not a good solution - by writing your own javascript function to capture query strings you are basically negating the purpose of GTM. Use a "Url" type variable instead, set "component type" to "query string" and in the "query key" input field enter the name of your parameter.
But to answer your question (even if your approach for that particular problem is not good), yes, you need to create a variable to read data from the dataLayer.
First you push the value to the dataLayer. The dataLayer is an array of objects, so you "push" a new object with key/value pairs:
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
"myDLKey":"myValue",
"event":"updateMyDLKey"
});
Then in the "variables" section of thr GTM interface, you create a dataLayer variable with the key whose value you want to retrieve.
There is basically no use case to change the dataLayer version. You can specify a default value, in case the key does not exist in the dataLayer, else the variable will be undefined.
Note that you need to push an event along with any new or updated key/value pairs, because the "event" key tells GTM to update its internal state; else the pushed values will be inaccessible.
There are some events that occur "naturally" - e.g. you do not need ab event in the dataLayer to capture values with the Url type variable, because in most cases there will be a pageload event (other "built in" events are DOM ready, window loaded, and click and submit if you have any of the built-in click or form variables enabled).