Back to the article · Zurück zum Artikel (Deutsch)
Example 08: The same element, fixed
Rule 4: Don't run code in the constructor that can throw
The constructor only creates the shadow root with a default text. localStorage is read in the connectedCallback, inside try/catch.
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 element is defined (
defined: true), and the failure is reported in the console instead of killing the element. Compare with example 07.
console.log() and errors on this page, the same text as in the developer toolsstorage blocked: SecurityError defined: true
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();
this.attachShadow({ mode: 'open' }).innerHTML = '<p>Nothing saved yet</p>';
}
connectedCallback() {
try {
const note = localStorage.getItem('note');
if (note) this.shadowRoot.querySelector('p').textContent = note;
} catch (error) {
console.log('storage blocked:', error.name);
}
}
}
customElements.define('saved-note', SavedNote);
console.log('defined:', document.querySelector('saved-note').matches(':defined'));
</script>