Skip to content

Commit 2804952

Browse files
authored
Merge pull request #1268 from cdrini/hotifx/localstorage-sandboxed-iframe
Fix error with localStorage in sandboxed iframe
2 parents df06472 + 4a4fdd4 commit 2804952

2 files changed

Lines changed: 18 additions & 2 deletions

File tree

src/plugins/tts/AbstractTTSEngine.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import PageChunkIterator from './PageChunkIterator.js';
2+
import { hasLocalStorage } from './utils.js';
23
/** @typedef {import('./utils.js').ISO6391} ISO6391 */
34
/** @typedef {import('./PageChunk.js')} PageChunk */
45

@@ -145,7 +146,7 @@ export default class AbstractTTSEngine {
145146
this.events.off('voiceschanged', this.updateBestVoice);
146147
this.voice = this.getVoices().find(voice => voice.voiceURI === voiceURI);
147148
// if the current book has a language set, store the selected voice with the book language as a suffix
148-
if (this.opts.bookLanguage) {
149+
if (this.opts.bookLanguage && hasLocalStorage()) {
149150
localStorage.setItem(`BRtts-voice-${this.opts.bookLanguage}`, this.voice.voiceURI);
150151
}
151152
if (this.activeSound) this.activeSound.setVoice(this.voice);
@@ -249,7 +250,7 @@ export default class AbstractTTSEngine {
249250
* @return {SpeechSynthesisVoice | undefined}
250251
*/
251252
static getMatchingStoredVoice(voices, bookLanguage) {
252-
const storedVoice = localStorage.getItem(`BRtts-voice-${bookLanguage}`);
253+
const storedVoice = hasLocalStorage() && localStorage.getItem(`BRtts-voice-${bookLanguage}`);
253254
return (storedVoice ? voices.find(v => v.voiceURI === storedVoice) : undefined);
254255
}
255256

src/plugins/tts/utils.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,18 @@ function searchForISO6391(language, columnsToSearch) {
6464
}
6565
return null;
6666
}
67+
68+
/**
69+
* Checks whether the current browser supports localStorage or
70+
* if the current context has access to it.
71+
* @return {boolean}
72+
*/
73+
export function hasLocalStorage() {
74+
try {
75+
return !!window.localStorage;
76+
} catch (e) {
77+
// Will throw in sandboxed iframe
78+
// DOMException: Window.localStorage getter: Forbidden in a sandboxed document without the 'allow-same-origin' flag.
79+
return false;
80+
}
81+
}

0 commit comments

Comments
 (0)