localStorage in GTM

Use localStorage in GTM

In case you prefer video format, you can watch it below. You can also subscribe to my YouTube channel!

In many web applications, localStorage (and sessionStorage) is actively used to store user values from the website. In some cases, you might need to extract some dynamic values from that storage to use in your tags. Let’s take a look at how to do that using Google Tag Manager.

Read values from localStorage

As this functionality is not available in GTM by default, we will need to utilize custom JavaScript variables.

For this, we can use the localStorage property and getItem() method in our script setup.

Here is an example code that you could use to read local storage value from a field named “key_name”. You should replace “key_name” with your own value depending on what you see in the console log.

function() {
  var keyValue = localStorage.getItem('key_name');
  return keyValue;
}

To use this example, you need to create a new Custom JavaScript variable and paste this code. Then replace ‘key_name’ with your own value.

Then you can use it as a regular User-Defined variable in your tags or triggers

Read values from sessionStorage

Very similar to local storage, to get session storage value, just replace ‘localStorage’ with ‘sessionStorage’.

function() {
  var keyValue = sessionStorage.getItem('key_name');
  return keyValue;
}

Extract value from JSON string

Often values in localStorage are available as a JSON string, so before we can effectively extract any information we would need to parse it as a JSON object.

Example JSON string:

{"v":"1.31", "metadata": "999", "type":"product" }

Let’s say you want to extract the “metadata” value from this example, for that you could use the following code:

function() {
  var obj = JSON.parse(localStorage.getItem('key_name'));
  return obj.metadata;
}

Here we are getting localStorage data with key_name and creating a JSON object from string. Then we are using obj.metadata to get information from object attribute named “metadata”.

If we would use this custom variable on provided JSON string above, it would return a value of – 999.

Fo your own scenario you would need to adjust the local storage key name and the attribute name (location) of the object.

For people who are a bit familiar with JavaScript, getting values from local storage might seem very straightforward, especially after having a couple of examples. You can read an additional article if you are interested in how to get read values from cookies in GTM as well.

One thought on “Use localStorage in GTM

  1. excellent! thank you, do you know any JS course oriented to marketing and GTM? it would be great for me.

Leave a Reply

Your email address will not be published. Required fields are marked *