Back to the article · Zurück zum Artikel (Deutsch)
Example 07: A constructor that reads blocked storage
Rule 4: Don't run code in the constructor that can throw
<saved-note> reads localStorage in its constructor. The page simulates blocked storage (as in a private window or with blocked cookies), so the read throws.
How to try it
- Open the console of the developer tools (F12, Cmd+Opt+I on a Mac). The "Console output" box on this page shows the same lines.
- The console shows a red error, followed by
defined: false.define()does not throw, the script keeps running, the element stays without an upgrade.
console.log() and errors on this page, the same text as in the developer toolsUncaught SecurityError: Storage is blocked defined: false
Live example
Source
<saved-note></saved-note>
<script type="module">
// Simulates blocked storage (private mode, blocked cookies).
Storage.prototype.getItem = () => {
throw new DOMException('Storage is blocked', 'SecurityError');
};
class SavedNote extends HTMLElement {
constructor() {
super();
// Rule 4: reads storage in the constructor, which can throw
const note = localStorage.getItem('note') ?? 'Nothing saved yet';
this.attachShadow({ mode: 'open' }).innerHTML = `<p>${note}</p>`;
}
}
customElements.define('saved-note', SavedNote);
console.log('defined:', document.querySelector('saved-note').matches(':defined'));
</script>