Retriving Local Storage and Session Storage Values with GTM
Local Storage & Session Storage are increasingly being used in web development to store user-defined values like web search data/location, session data etc. Gradually it’s becoming something that web-analytics people need to know/use and there are no predefined variables in GTM to obtain these values.
You can use below JS script in CustomJs variable to return the values in Local Storage or Session storage.
Local Storagefunction() { var location = localStorage.getItem('pickup_location'); return location; }
Here pickup_location
is the KEY name of the Local Storage. You can also define a javascript variable in GTM for above with value – localstorage.pickup_location
If the Local Storage is JSON formatted and arrayed, one could use Json Parse to obtain the values of array members.
function() { var obj = JSON.parse(localStorage.getItem('pickup_location')); return obj.city; }
Here pickup_location
will be the name of the LocalStorage Key and city
is the array member name.
Session Storage follows the same formmating of Local Storage with small difference in naming.
function() { var location = sessionStorage.getItem('pickup_location'); return location; }