Skip to content

Commit

Permalink
Catch localStorage usage exception (#1038)
Browse files Browse the repository at this point in the history
* Catch localStorage usage exception

* Prettier
  • Loading branch information
NiedziolkaMichal authored Jan 19, 2023
1 parent 9d5905d commit bf461ca
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions editor/js/editor-libs/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,44 @@ function addPostMessageListener() {
}
}
body.classList.add("theme-" + event.data.theme);
localStorage.setItem("theme", event.data.theme);
storeItem("theme", event.data.theme);
}
},
false
);
}

document.addEventListener("DOMContentLoaded", () => {
const theme = localStorage.getItem("theme");
const theme = getStorageItem("theme");
if (theme !== null) {
document.querySelector("body").classList.add("theme-" + theme);
}
});

/**
* Adds key & value to {@link localStorage}, without throwing an exception when it is unavailable
*/
function storeItem(key, value) {
try {
localStorage.setItem(key, value);
} catch (err) {
console.warn(`Unable to write ${key} to localStorage`, err);
}
}

/**
* @returns the value of a given key from {@link localStorage}, or null when the key wasn't found.
* It doesn't throw an exception when {@link localStorage} is unavailable
*/
function getStorageItem(key) {
try {
return localStorage.getItem(key);
} catch (err) {
console.warn(`Unable to read ${key} from localStorage`, err);
return null;
}
}

function sendOwnHeight() {
if (parent) {
parent.postMessage(
Expand Down

0 comments on commit bf461ca

Please sign in to comment.