Can't read local storage in javascript function

I’m trying to read Magento’s shopping cart with Tag Manager. This functions well in console:

JSON.parse(localStorage.getItem('mage-cache-storage')).cart.items

But custom javascript function in the tag manager returns undefined:

function() {
return JSON.parse(localStorage.getItem('mage-cache-storage')).cart.items;
}

What did I miss?

Hi Mikko,

maybe your JS function (being loaded from a different host) does not have access to the mage-cache-storage key in localStorage due to partitioned browser storage? That might be the case in Brave for example(?)

best,
Markus

2 Likes

I’d try also with such code:

function() {
 try {
  return JSON.parse(localStorage.getItem('mage-cache-storage')).cart.items;
 } catch(e) {
  return null;
 }
}

It might improve the situation when you ask for the value before it’s available. Of course, here I assume that you’ll use it at later stage (one of the following datalayer events).

Thanks, Markus - I think you’re right. I was using Safari… So the devs need to improve the datalayer for me - no shortcuts here :slight_smile:

Mikko

2 Likes