clock menu more-arrow no yes mobile

Filed under:

Reliably Testing for Local Storage

Recently I was tasked with figuring out why comments had stopped showing up on certain sites when users were using Safari Private Browsing mode. Previously, comments had loaded fine. Thanks to some help from coworkers, we traced the issue back to LocalStorage — specifically the commenting system was checking for its presence in the window object, and, if found, proceeding to rely on it.

The bug that popped up carried with it a cryptic error in Safari's console:

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

The code had recently been updated and was doing a check to confirm that localStorage was present and that setItem was an available function. This test is good enough for most browsers, but it was breaking in Safari while using Private Browsing mode, because Safari defines the API but sets its cache limit to 0 — meaning the objects are defined but nothing can be stored. Attempting to save anything to localStorage will throw the above error. To work around this, we had to change our test to match Modernizr's, which not only confirms the presence of the API but also confirms that it is working. Below you can see the old version of the function and the new, which succeeded in squashing the bug.