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.
This commit is contained in:
Ben Harris
2023-05-30 15:07:41 +02:00
parent b6c842a28c
commit 6a41c0b7a0

View File

@ -807,7 +807,13 @@ mergeInto(LibraryManager.library, {
*/
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 @@ mergeInto(LibraryManager.library, {
* 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);
}
}
});