Peter Weightman
Back

Error using localStorage on Safari

In Safari on mac, if you go to Preferences -> Privacy, there's an option to "Block all cookies". If you enable this, any time a website tries to use localStorage, it'll error with: SecurityError: The operation is insecure..

Even doing console.log(localStorage) will cause this error, which means just doing e.g. localStorage?.getItem('key') would crash your script if you aren't catching errors.

I've come across this MDN article with a function to check if storage is available. I now use this on my site (which I probably should've anyway), so if Safari users with this preference enabled use dark mode on my site it'll work but won't persist after reload/revisit.