UI Architect, Full Stack Web Developer – San Francisco Bay Area (Walnut Creek), CA
UI Architect, Full Stack Web Developer – San Francisco Bay Area (Walnut Creek), CA

Javascript localStorage & sessionStorage gotchas

IMG_3694
The tabs open but the links don’t work?!

So you write some code, validate the feature, send it off to QA, and move on to something else.  The last thing you expect is to have a QA engineer come back and say that your code doesn’t work.  When that happens, you begin the process of identifying the differences (or the singular difference) between the tester’s system and yours.

I opened the site on my phone, it works.  I open the site on his phone, it doesn’t work.

We both have iPhones.  Both have the same iOS version.  Both have the same browser.  My links work, his don’t.  Go figure.  Wait, why is his border black and mine is white?  Ahh, he’s in private browsing mode.  Well that shouldn’t make any difference, should it?  Links are links, right?

So I open an incognito tab, go to the site, and sure enough my links don’t work either.  Who would’ve guessed?

So, I hook up my phone to my computer to open my dev tools and start scouring the console log for errors.  This one looks unusual:

QuotaExceededError: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota.

Turns out I had added a script to save the open tabs to sessionStorage, so subsequent page views would display the open tabs for the user when they opened the hamburger menu.  Safari’s mobile browser not only disables localStorage and sessionStorage in private mode, but also throws a fatal error!  The script stops running.  In this case, the links did not respond to tap events.

The problem here was pretty easy to fix.  Test for sessionStorage and use a try/catch to silently ignore the error:

 if (typeof sessionStorage === 'object') {
   try {
     sessionStorage.setItem('openMobileMenuTabs', JSON.stringify(openMobileTabs));
   } catch (e) {
     // silently ignore javascript error when sessionStorage is unavailable. The most likely case is Private browsing mode.
   }
 }

Lesson learned.  Always test your code in private mode on a mobile device when using localStorage or sessionStorage

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.