Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Use `event.preventDefault()` for beforeunload; avoid deprecated `returnValue`
Trigger the unsaved-changes prompt with `event.preventDefault()`; the deprecated `event.returnValue` and its custom string are ignored by modern browsers.
Bad example
| 1 | window.addEventListener('beforeunload', (event) => { |
| 2 | event.preventDefault(); |
| 3 | // deprecated; custom string ignored by all modern browsers |
| 4 | event.returnValue = 'You have unsaved changes!'; |
| 5 | }); |
Explanation (EN)
Setting `event.returnValue` is deprecated per spec and the custom message is ignored — browsers always show their own generic prompt, so the assignment is dead weight.
Objašnjenje (HR)
Postavljanje `event.returnValue` je zastarjelo prema specifikaciji i prilagodena poruka se ignorira — preglednici uvijek prikazu vlastiti genericki upit, pa je dodjela mrtav teret.
Good example
| 1 | window.addEventListener('beforeunload', (event) => { |
| 2 | if (hasUnsavedChanges) { |
| 3 | event.preventDefault(); |
| 4 | } |
| 5 | }); |
Explanation (EN)
Modern browsers trigger the built-in confirmation dialog from `preventDefault()` alone, so no deprecated API or ignored custom string is needed.
Objašnjenje (HR)
Moderni preglednici pokrecu ugradeni dijalog potvrde samo iz `preventDefault()`, pa nije potreban zastarjeli API ni ignorirana prilagodena poruka.
Exceptions / Tradeoffs (EN)
If you must support an older browser that still requires `event.returnValue = ''`, keep it but document why; the empty string is enough since the text is never displayed.
Iznimke / Tradeoffi (HR)
Ako moras podrzati stariji preglednik koji jos zahtijeva `event.returnValue = ''`, zadrzi ga ali dokumentiraj zasto; prazan string je dovoljan jer se tekst nikad ne prikazuje.