shithub: puzzles

Download patch

ref: 6a41c0b7a0c0f8299a86e5d33e7008ced3911924
parent: b6c842a28cf6597df063fcff35079c3e3982381e
author: Ben Harris <bjh21@bjh21.me.uk>
date: Tue May 30 11:07:41 EDT 2023

js: handle exceptions when accessing localStorage

Trying to access window.localStorage will generate an exception if the
local storage is for some reason inaccessible.  This can be
demonstrated in Firefox by configuring it to block a site from using
site data.  Writing to local storage might also cause an exception if,
for instance, the quota of data for a site is exceeded.

If an exception is raised while loading preferences we log the fact
but don't make any report to the user, behaving as if no preferences
were found.  This avoids annoying the user on every visit to a puzzle
page if they're not trying to use preferences.

If something goes wrong when saving, we do currently report that to
the user in an alert box.  This seems reasonable since it's in
response to an explicit user action.

--- a/emcclib.js
+++ b/emcclib.js
@@ -807,7 +807,13 @@
      */
     js_save_prefs: function(buf) {
         var prefsdata = UTF8ToString(buf);
-        localStorage.setItem(location.pathname + " preferences", prefsdata);
+        try {
+            localStorage.setItem(location.pathname + " preferences", prefsdata);
+        } catch (error) {
+            // Tell the user their preferences have not been saved.
+            console.error(error);
+            alert("Saving of preferences failed: " + error.message);
+        }
     },
 
     /*
@@ -817,9 +823,16 @@
      * pass it back in as a string, via prefs_load_callback.
      */
     js_load_prefs: function(me) {
-        var prefsdata = localStorage.getItem(location.pathname+" preferences");
-        if (prefsdata !== undefined && prefsdata !== null) {
-            prefs_load_callback(me, prefsdata);
+        try {
+            var prefsdata =
+                localStorage.getItem(location.pathname + " preferences");
+            if (prefsdata !== undefined && prefsdata !== null) {
+                prefs_load_callback(me, prefsdata);
+            }
+        } catch (error) {
+            // Log the error but otherwise pretend the settings were
+            // absent.
+            console.warn(error);
         }
     }
 });