Imran Khan
← Back to blog
Beyond unload: Save Drafts and Restore Pages Safely
Page lifecyclebfcacheJavaScriptWeb StorageUXbrowser testing

Beyond unload: Save Drafts and Restore Pages Safely

By ··11m read

Build a draft editor that recovers saved text, detects stale copies, and reports storage failures.

A user writes a reply, switches to another tab to check a fact, and returns to an empty editor. Another user presses Back and gets an older copy of a document that a second tab has already changed. Both failures can happen in an application with a perfectly working Save button.

Save recoverable work while the user is working. Treat page visibility and navigation events as additional opportunities to checkpoint and manage resources. On return, distinguish a new document from a restored document, then reconcile stored state before writing anything back. There is no final callback that makes this sequence unnecessary.

The companion editor makes both failures observable: it checkpoints a small text draft, exposes storage errors and coordinates cooperating tabs. Its source viewer and download follow the design below.

The agentic browsing guide covers navigable flows and useful failure states. This is a narrower implementation question: what must remain true when the browser stops running your page?

Separate the draft, the stored copy, and the live page

Three objects have different lifetimes. On narrow screens, focus a table region to scroll it with the keyboard.

ObjectWhat it containsWhat can happen to it
Working draftCurrent text in the editor and its in-memory stateSurvives a pause of the same document; disappears when that document is destroyed
Local checkpointA validated, versioned copy in browser storageCan be reopened by a new document; may be unavailable, cleared, or replaced by another cooperating editor
Live resourcesTimers, connections and subscriptions owned by this documentNeed bounded ownership and deliberate pause/resume behavior

The back/forward cache, or bfcache, can retain the document, DOM and JavaScript heap in memory. HTTP caching retains network responses. A new page loaded from cached files is still a different document with newly initialized application state. Neither mechanism is your durable draft store. How bfcache works.

This distinction changes the recovery algorithm. A fresh document starts by loading a checkpoint. A restored document already has an editor and an old view of the world; blindly running the startup loader can overwrite useful working text.

A restored page can overwrite newer work

Consider two cooperating tabs:

  1. Tab A saves “First draft” and navigates away.
  2. Tab B opens the same document and saves “Revised draft.”
  3. Tab A returns with its earlier in-memory state.

If A immediately checkpoints its old text on return, it can erase B’s newer work while confidently reporting a successful save. Preserving the page has made an old snapshot convenient to resume, not authoritative.

The return path needs four rules:

  1. Read the current checkpoint after acquiring the writer role, before allowing another write.
  2. Preserve the editor’s working text when the stored revision has changed.
  3. Ask which copy to keep. Replacing the newer checkpoint requires an explicit choice against its current revision.
  4. Resume visible resources once, even when several lifecycle events request it.

The editor below follows these rules. A changed revision leaves the old text visible and presents Load stored draft and Keep my text and save a new revision choices.

An incoming storage event is useful notification, but not a lock. It is sent to other documents sharing the storage area, not to the writer itself. Storage events.

Nor does “read revision, compare revision, write record” create an atomic compare-and-swap over localStorage. For its cooperating editors, this lab uses the Web Locks API to grant one writer role at a time. It releases that role when the page is hidden and reconciles after acquiring it again. A browser without this capability gets a recovery/export path rather than an unprotected concurrent editor. Other scripts on the same origin can ignore that agreement; it is application coordination, not a security boundary. Web Locks.

The same principle applies when moving to a server: the server must enforce the expected revision. A client-side lock cannot serialize edits arriving from another browser or device.

Why migrate away from unload now

Chrome’s documented rollout of disabling unload by default completed with Chrome 155 on October 6, 2026. Its October 16 documentation lists 100% of Chrome page loads, with opt-outs still available and different behavior possible on iOS. Chrome’s rollout and exceptions.

The persistence problem predates that change: a background page can disappear without another JavaScript callback. Save while editing; use lifecycle events to manage a recoverable page.

Make a successful write the boundary for “saved”

I limited this example to 20,000 UTF-16 code units of plain text. The editor attempts a synchronous checkpoint on every input. After setItem succeeds, a new document can read the accepted copy without waiting for a debounced callback. Saved locally means browser-storage acceptance; physical durability and retention are separate concerns.

Web Storage runs synchronously on the JavaScript thread, so this approach suits a small draft. Large documents and attachments need an asynchronous store such as IndexedDB, with transaction completion, ordering and pending-write UX. Web Storage behavior.

The application maintains separate working text and last successfully stored text. Those values can diverge after an error. It reports a local checkpoint only after the storage adapter succeeds. Clearing the editor to an empty string also creates a real checkpoint; an empty draft must not accidentally mean “there is no record.”

A schema version and a revision token help identify what was read. They do not make untrusted JSON valid. On startup, the lab checks the record before using it. Corrupt JSON, unsupported versions and invalid fields produce a recovery state; the application does not replace the unrecognized record with a blank draft just to make startup succeed.

For your own product, identify the document and account in the storage design and implement a retention policy. A prefixed key is a naming convention, not an access boundary: Web Storage is shared within an origin, with no isolation by URL path. Avoid putting sensitive production material into a casual demo origin. WHATWG Web Storage.

Use lifecycle events according to their job

Each signal has a specific responsibility:

SignalApplication responsibility in this exampleAssumption to avoid
InputUpdate working text and attempt a checkpoint while execution is availableThere will always be time for a later timer
visibilitychange to hiddenMake an additional bounded checkpoint attempt, pause visible work and release the writer roleHidden means permanently closed
pagehidePause resources and release ownership idempotentlyThe event always arrives before termination
pageshowReconcile the stored revision; distinguish a confirmed bfcache return with persistedEvery pageshow means the page is currently visible
Visibility returning to visibleReconcile and reacquire ownership before enabling editingThe old heap is still the newest copy

Read document.visibilityState inside a visibility handler; the event does not carry the new state. Use hidden as an additional checkpoint opportunity. Visibility change.

pagehide works with bfcache. It can be absent when a mobile user switches applications and later kills the browser, so recovery depends on the earlier checkpoint. Pagehide behavior.

The example has one visible-work timer so duplicate initialization is observable. Starting is a no-op when a timer already exists; stopping is a no-op when it does not. A restored page must not accumulate a second interval because two lifecycle signals both suggested resuming.

Chromium’s freeze, resume and desktop document.wasDiscarded can provide additional diagnostics. They are not the foundation of the portable save path. A discarded page gets a new document when reopened; it cannot run code at the moment of discard. Page Lifecycle reference.

A failed local write must remain visible

Storage failure is a normal branch of the application. A write can exceed quota; accessing storage can also be denied. The correct response is not to relabel the in-memory text as saved. Storage write errors.

Use the lab’s explicit failure control, then edit the text. The stored checkpoint should stay unchanged, the working text should remain visible, and the status should identify unsaved work. Retry after removing the injected failure, or download the current text through a deliberate user action. The failure control exercises the application error path; it does not claim to fill the browser’s real quota.

The user can download the working text while storage is failing. Keep that action available in the editor, where its outcome can be checked.

beforeunload is reserved for this unresolved-loss state. The lab removes its listener once the pending work is safely resolved. A warning may depend on prior user interaction, cannot supply arbitrary dialog text, and is itself unreliable on mobile. It is a last chance to intervene, not the persistence mechanism. Beforeunload constraints.

Local storage is also not an archival guarantee. Browser policies, private browsing and user clearing can remove it. Choose retention, export and server synchronization according to the value of the work. Storage quotas and retention.

Run the editor on a dedicated local origin

The companion lab is separate from the blog application. Download the complete lab ZIP, extract it into one directory and follow the README. The server binds to loopback and serves only the example’s known files.

Inspect the individual sources below. Choose a file to read its code, copy it, or download the original.

Source files

10 files
app.mjs

Browser lifecycle adapter

212 lines · JavaScriptOpen fileDownload
import { createDraftController, createPausableTimer, DRAFT_KEY, WRITER_LOCK } from './core.mjs';

const $ = (id) => document.getElementById(id);
const documentId = crypto.randomUUID();
const editor = $('draft');
let hasWriterLock = false;
let releaseWriterLock = null;
let acquiring = null;
let leaving = false;
let beforeUnloadAttached = false;
let hasUserInput = false;
let lifecycleEpoch = 0;
let ticks = 0;

const storage = {
  getItem(key) { return window.localStorage.getItem(key); },
  setItem(key, value) {
    if ($('fail-writes').checked) throw new DOMException('Synthetic write failure.', 'QuotaExceededError');
    window.localStorage.setItem(key, value);
  },
};
const draft = createDraftController(storage, { writerId: documentId });
editor.value = draft.snapshot().text;
$('document-id').textContent = documentId;
$('user-agent').textContent = navigator.userAgent;
$('discarded').textContent = 'wasDiscarded' in document ? String(document.wasDiscarded) : 'API not supported';

function log(message) {
  const item = document.createElement('li');
  const time = document.createElement('time');
  time.textContent = new Date().toLocaleTimeString('en-GB', { hour12: false });
  item.append(time, document.createTextNode(message));
  $('event-log').prepend(item);
  while ($('event-log').children.length > 30) $('event-log').lastElementChild.remove();
}

const timer = createPausableTimer({ tick() { $('ticks').textContent = String(++ticks); } });
function updateResources() {
  if (!leaving && document.visibilityState === 'visible') timer.start();
  else timer.stop();
  $('timer-state').textContent = timer.isRunning() ? 'Running' : 'Paused';
  $('visibility').textContent = document.visibilityState;
}

function warnBeforeUnload(event) {
  if (!draft.snapshot().dirty) return;
  event.preventDefault();
  event.returnValue = '';
}

function render() {
  const state = draft.snapshot();
  const labels = { empty: 'No stored draft', saved: 'Saved locally', unsaved: 'Not saved locally', error: 'Local storage error', conflict: 'Conflict — choice required' };
  $('save-status').textContent = labels[state.status];
  $('save-status').dataset.status = state.status;
  $('char-count').textContent = state.text.length.toLocaleString('en-US');
  $('revision').textContent = state.revision ? `Revision ${state.revision}` : 'No stored revision';
  $('save-detail').textContent = state.error ?? (state.dirty
    ? 'This page still holds text that has not been saved. Retry, resolve a conflict, or download it before leaving.'
    : 'Local saves stay in this browser profile and origin. They are not a backup or a server sync.');
  $('conflict').hidden = !state.conflict;
  if (state.conflict) {
    $('conflict-detail').textContent = state.conflict.kind === 'invalid'
      ? state.conflict.reason
      : state.conflict.kind === 'absent'
        ? 'The stored draft was removed. Loading it clears this editor. Your current text has not been replaced.'
        : `Another revision (${state.conflict.record.revision}) is stored. Your current text has not been replaced.`;
  }
  editor.readOnly = !hasWriterLock;
  $('retry-save').disabled = !navigator.locks;
  $('load-stored').disabled = !hasWriterLock || state.conflict?.kind === 'invalid';
  $('keep-mine').disabled = !hasWriterLock;
  $('lock-state').textContent = hasWriterLock ? 'Owned by this document' : navigator.locks ? 'Not owned' : 'API not supported';
  $('ownership-notice').hidden = hasWriterLock;
  $('ownership-notice').textContent = !navigator.locks
    ? 'Web Locks is unavailable. This lab is read-only here; you can inspect or download a recovered draft. Serve it over loopback HTTP or HTTPS in a browser with Web Locks support.'
    : 'Another document may hold the writer lock. This editor is read-only until it acquires the lock. Switch away from the other tab, then choose Retry save.';
  if (state.dirty !== beforeUnloadAttached) {
    if (state.dirty) window.addEventListener('beforeunload', warnBeforeUnload);
    else window.removeEventListener('beforeunload', warnBeforeUnload);
    beforeUnloadAttached = state.dirty;
    log(`beforeunload warning ${state.dirty ? 'attached: text is not persisted' : 'removed: text is persisted'}`);
  }
}

function checkpoint(reason) {
  if (hasWriterLock) {
    const result = draft.save();
    log(`${reason}: ${result.status}${result.dirty ? ', text not persisted' : ''}`);
  }
  render();
}

function releaseLock(reason) {
  if (!hasWriterLock) return;
  hasWriterLock = false;
  releaseWriterLock?.();
  releaseWriterLock = null;
  log(`writer lock released: ${reason}`);
  render();
}

function acquireLock() {
  if (hasWriterLock || acquiring || leaving || document.visibilityState !== 'visible' || !navigator.locks) return acquiring;
  acquiring = navigator.locks.request(WRITER_LOCK, { mode: 'exclusive', ifAvailable: true }, async (lock) => {
    if (!lock) { log('writer lock unavailable'); render(); return; }
    if (leaving || document.visibilityState !== 'visible') return;
    hasWriterLock = true;
    draft.reconcile();
    log('writer lock acquired; stored revision checked without replacing editor text');
    render();
    await new Promise((resolve) => { releaseWriterLock = resolve; });
  }).catch((error) => {
    log(`writer lock error: ${error.name}`);
    hasWriterLock = false;
    render();
  }).finally(() => { acquiring = null; });
  return acquiring;
}

editor.addEventListener('input', () => {
  if (!hasWriterLock) return;
  hasUserInput = true;
  const result = draft.edit(editor.value);
  log(`input: ${result.status}`);
  render();
});
$('retry-save').addEventListener('click', () => {
  if (hasWriterLock) checkpoint('manual retry');
  else acquireLock();
});
$('load-stored').addEventListener('click', () => {
  if (!hasWriterLock) return;
  const result = draft.chooseStored();
  if (!result.conflict && result.status !== 'error') editor.value = result.text;
  log(`explicit choice: load stored draft (${result.status})`);
  render();
});
$('keep-mine').addEventListener('click', () => {
  if (!hasWriterLock) return;
  const result = draft.keepMine();
  log(`explicit choice: keep current text (${result.status})`);
  render();
});
$('download').addEventListener('click', () => {
  const url = URL.createObjectURL(new Blob([draft.snapshot().text], { type: 'text/plain;charset=utf-8' }));
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.download = 'local-draft.txt';
  anchor.click();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
  log('manual download requested; local save status unchanged');
});
$('fail-writes').addEventListener('change', () => {
  log(`synthetic write failure ${$('fail-writes').checked ? 'enabled' : 'disabled'}; no browser lifecycle event simulated`);
});
$('clear-log').addEventListener('click', () => $('event-log').replaceChildren());

document.addEventListener('visibilitychange', () => {
  log(`visibilitychange: ${document.visibilityState}`);
  if (document.visibilityState === 'hidden') {
    checkpoint('hidden checkpoint');
    releaseLock('hidden');
  } else {
    draft.reconcile();
    acquireLock();
  }
  updateResources();
  render();
});
window.addEventListener('pagehide', (event) => {
  lifecycleEpoch++;
  leaving = true;
  log(`pagehide: persisted=${event.persisted}`);
  checkpoint('pagehide checkpoint');
  releaseLock('pagehide');
  updateResources();
});
window.addEventListener('pageshow', (event) => {
  const epoch = ++lifecycleEpoch;
  leaving = false;
  $('persisted').textContent = String(event.persisted);
  log(`pageshow: persisted=${event.persisted}`);
  draft.reconcile();
  if (!event.persisted) {
    const hydrateFreshDocument = () => {
      if (hasUserInput || leaving || epoch !== lifecycleEpoch) return;
      // History can restore native form state after pageshow. A new document
      // uses its validated storage snapshot; a bfcache document keeps its DOM.
      if (editor.value !== draft.snapshot().text) {
        editor.value = draft.snapshot().text;
        log('fresh document: native form restoration reconciled with validated draft');
      }
    };
    hydrateFreshDocument();
    setTimeout(hydrateFreshDocument, 0);
  }
  updateResources();
  acquireLock();
  render();
});
window.addEventListener('storage', (event) => {
  if (event.key !== DRAFT_KEY && event.key !== null) return;
  draft.reconcile();
  log('storage event: revision checked; in-memory editor text preserved');
  render();
});

log(`document boot: ${documentId}`);
updateResources();
render();
acquireLock();
core.mjs

Application rules

125 lines · JavaScriptOpen fileDownload
export const MAX_TEXT_LENGTH = 20_000;
export const DRAFT_KEY = 'beyond-unload:draft:v1';
export const WRITER_LOCK = 'beyond-unload:draft-writer:v1';

export function parseDraft(raw) {
  if (raw === null) return { kind: 'absent', record: null };
  let record;
  try { record = JSON.parse(raw); }
  catch { return { kind: 'invalid', reason: 'Stored draft is not valid JSON.' }; }
  if (!record || typeof record !== 'object' || Array.isArray(record)) {
    return { kind: 'invalid', reason: 'Stored draft is not an object.' };
  }
  if (record.version !== 1) {
    return { kind: 'invalid', reason: 'Unsupported draft version. The stored copy was preserved.' };
  }
  if (typeof record.text !== 'string' || record.text.length > MAX_TEXT_LENGTH
    || typeof record.revision !== 'string' || !/^[a-zA-Z0-9_-]{1,80}:\d{1,12}$/.test(record.revision)
    || typeof record.savedAt !== 'number' || !Number.isSafeInteger(record.savedAt) || record.savedAt < 0
    || Object.keys(record).some((key) => !['version', 'text', 'revision', 'savedAt'].includes(key))) {
    return { kind: 'invalid', reason: 'Stored draft failed schema validation. The stored copy was preserved.' };
  }
  return { kind: 'valid', record };
}

// The browser adapter must hold WRITER_LOCK while mutating this controller.
// localStorage has no atomic compare-and-swap: revisions alone are not a lock.
export function createDraftController(storage, {
  key = DRAFT_KEY, writerId = 'writer', now = Date.now,
} = {}) {
  if (!/^[a-zA-Z0-9_-]{1,80}$/.test(writerId)) throw new TypeError('Invalid writer ID.');
  let sequence = 0;
  let baseRaw;
  let state = { text: '', dirty: false, status: 'empty', error: null, conflict: null, revision: null, savedAt: null };

  const read = () => {
    try { return { ok: true, raw: storage.getItem(key) }; }
    catch (error) {
      state = { ...state, status: 'error', error: `Local storage could not be read (${error.name || 'Error'}).` };
      return { ok: false };
    }
  };
  const conflict = (raw) => {
    const parsed = parseDraft(raw);
    state = { ...state, status: 'conflict', error: null, conflict: parsed };
    return snapshot();
  };
  const snapshot = () => ({ ...state, conflict: state.conflict ? structuredClone(state.conflict) : null });

  const initial = read();
  if (initial.ok) {
    baseRaw = initial.raw;
    const parsed = parseDraft(baseRaw);
    if (parsed.kind === 'valid') {
      state = { ...state, text: parsed.record.text, status: 'saved', revision: parsed.record.revision, savedAt: parsed.record.savedAt };
    } else if (parsed.kind === 'invalid') conflict(baseRaw);
  }

  function inspectStorage(forSave) {
    const current = read();
    if (!current.ok) return snapshot();
    if (baseRaw === undefined && current.raw === null) baseRaw = null;
    if (current.raw !== baseRaw) return conflict(current.raw);
    if (state.conflict) return snapshot();
    // A successful read does not demonstrate that a failed write can succeed.
    if (!forSave && state.status === 'error') return snapshot();
    state = { ...state, status: state.dirty ? 'unsaved' : (state.revision ? 'saved' : 'empty'), error: null };
    return snapshot();
  }

  function reconcile() { return inspectStorage(false); }

  function save() {
    if (state.text.length > MAX_TEXT_LENGTH) {
      state = { ...state, status: 'error', error: `Draft exceeds ${MAX_TEXT_LENGTH.toLocaleString('en-US')} UTF-16 code units.` };
      return snapshot();
    }
    const checked = inspectStorage(true);
    if (checked.status === 'error' || checked.status === 'conflict' || !state.dirty) return snapshot();
    const record = { version: 1, text: state.text, revision: `${writerId}:${++sequence}`, savedAt: now() };
    const raw = JSON.stringify(record);
    try { storage.setItem(key, raw); }
    catch (error) {
      state = { ...state, status: 'error', error: `Local save failed (${error.name || 'Error'}). Your text is still in this page.` };
      return snapshot();
    }
    baseRaw = raw;
    state = { ...state, dirty: false, status: 'saved', error: null, conflict: null, revision: record.revision, savedAt: record.savedAt };
    return snapshot();
  }

  return {
    snapshot, reconcile, save,
    edit(text) {
      if (typeof text !== 'string') throw new TypeError('Draft text must be a string.');
      state = { ...state, text, dirty: true };
      return save();
    },
    keepMine() {
      const current = read();
      if (!current.ok) return snapshot();
      baseRaw = current.raw;
      state = { ...state, dirty: true, conflict: null, error: null, status: 'unsaved' };
      return save();
    },
    chooseStored() {
      const current = read();
      if (!current.ok) return snapshot();
      const parsed = parseDraft(current.raw);
      if (parsed.kind === 'invalid') return conflict(current.raw);
      baseRaw = current.raw;
      state = { text: parsed.record?.text ?? '', dirty: false, status: parsed.kind === 'valid' ? 'saved' : 'empty', error: null,
        conflict: null, revision: parsed.record?.revision ?? null, savedAt: parsed.record?.savedAt ?? null };
      return snapshot();
    },
  };
}

export function createPausableTimer({ startInterval = setInterval, stopInterval = clearInterval, tick }) {
  let handle = null;
  return {
    start() { if (handle === null) handle = startInterval(tick, 1000); },
    stop() { if (handle !== null) { stopInterval(handle); handle = null; } },
    isRunning() { return handle !== null; },
  };
}
index.html

Editor HTML

34 lines · HTMLOpen fileDownload
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="color-scheme" content="dark"><meta name="robots" content="noindex">
  <title>Draft recovery lab · Critical Developer</title>
  <link rel="stylesheet" href="./style.css">
  <script type="module" src="./app.mjs"></script>
</head>
<body>
  <main class="shell">
    <header class="masthead"><a class="brand" href="https://blog.criticaldeveloper.com">CD<span> / FIELD NOTES</span></a><span class="edition">BROWSER LIFECYCLE · 01</span></header>
    <div class="intro"><p class="eyebrow">SAVE EARLY. RESUME CAREFULLY.</p><h1>A draft worth<br><em>coming back to.</em></h1><p class="lede">A small, local editor for observing save failures, page restoration and conflicts. Use synthetic text only.</p></div>
    <section class="workspace" aria-label="Draft editor and observations">
      <div class="editor-panel">
        <div class="panel-top"><label for="draft">YOUR LOCAL DRAFT</label><span id="save-status" role="status" aria-live="polite">Starting…</span></div>
        <div id="ownership-notice" class="notice" role="status">Acquiring the writer lock…</div>
        <div id="conflict" class="notice notice-warning" hidden><strong>Stored copy changed.</strong><p id="conflict-detail"></p><div class="actions"><button id="load-stored" type="button">Load stored draft</button><button id="keep-mine" type="button">Keep my text and save a new revision</button></div></div>
        <textarea id="draft" maxlength="20000" autocomplete="off" spellcheck="false" readonly aria-describedby="draft-limit save-detail" placeholder="Write a synthetic note. Every input attempts a local save."></textarea>
        <div class="editor-bottom"><span id="draft-limit"><span id="char-count">0</span> / 20,000 code units</span><span id="revision">No stored revision</span></div>
        <p id="save-detail" class="save-detail">Local saves stay in this browser profile and origin. They are not a backup or a server sync.</p>
        <div class="toolbar"><button id="retry-save" type="button">Retry save</button><button id="download" type="button">Download current text</button><a class="button button-primary" id="go-away" href="./away.html">Leave and come back <span aria-hidden="true">↗</span></a></div>
        <label class="fault-control"><input type="checkbox" id="fail-writes"> Simulate a failed local write</label>
      </div>
      <aside class="observations">
        <p class="eyebrow">OBSERVE THE DOCUMENT</p>
        <dl><div><dt>Document</dt><dd id="document-id"></dd></div><div><dt>Visibility</dt><dd id="visibility"></dd></div><div><dt>Restored from bfcache</dt><dd id="persisted">Not observed yet</dd></div><div><dt>Was discarded</dt><dd id="discarded"></dd></div><div><dt>Resource timer</dt><dd><span id="timer-state">Paused</span> · <span id="ticks">0</span> ticks</dd></div><div><dt>Writer lock</dt><dd id="lock-state">Waiting</dd></div><div><dt>Browser (reported user agent)</dt><dd id="user-agent"></dd></div></dl>
        <div class="log-heading"><h2>Event log</h2><button type="button" id="clear-log" class="text-button">Clear</button></div><ol id="event-log" aria-label="Recent lifecycle events"></ol>
      </aside>
    </section>
    <footer><p>A successful write is labelled <strong>Saved locally</strong>. A restored page keeps its in-memory text until you explicitly resolve a conflict. Background pages release this example’s cooperative writer lock.</p><p><a href="./exit-only.html">Compare the unload-only control</a><span aria-hidden="true"> ↗</span> · <a href="./README.md">Run and inspect the lab</a></p></footer>
  </main>
</body>
</html>
style.css

Editor styles

2 lines · CSSOpen fileDownload
:root{color-scheme:dark;--bg:#101817;--panel:#17221f;--ink:#ecf5ef;--muted:#a4b7ad;--line:#34453d;--mint:#88edb9;--warning:#ffce8b;--display:Georgia,'Times New Roman',serif;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:var(--bg);color:var(--ink)}
*{box-sizing:border-box}body{margin:0}a{color:var(--mint);text-underline-offset:.23em}button,input,textarea{font:inherit}button,a.button{transition:background .15s,color .15s}button:focus-visible,a:focus-visible,input:focus-visible{outline:2px solid var(--mint);outline-offset:4px}button{cursor:pointer}button:disabled{cursor:not-allowed;opacity:.45}[hidden]{display:none!important}.shell{width:min(1260px,100% - 64px);margin:auto}.masthead{display:flex;justify-content:space-between;align-items:center;padding:30px 0;border-bottom:1px solid var(--line);gap:24px}.brand{font-size:22px;letter-spacing:-1px;text-decoration:none;color:var(--ink);font-weight:800}.brand span,.edition{font:11px ui-monospace,monospace;letter-spacing:.12em;color:var(--muted)}.intro{padding:58px 0 40px;max-width:760px}.eyebrow{font:11px ui-monospace,monospace;color:var(--mint);letter-spacing:.12em;margin:0 0 20px}h1{font-family:var(--display);font-size:clamp(48px,6vw,80px);font-weight:400;letter-spacing:-.045em;line-height:1.01;margin:0 0 23px}h1 em{font-weight:400;color:var(--mint)}.lede{font-size:17px;line-height:1.6;color:var(--muted);max-width:620px;margin:0}.workspace{display:grid;grid-template-columns:minmax(0,1fr) 305px;gap:24px;align-items:start}.editor-panel,.observations{border:1px solid var(--line);background:var(--panel);border-radius:3px}.panel-top{display:flex;gap:16px;justify-content:space-between;align-items:center;padding:20px 22px;border-bottom:1px solid var(--line);font:11px ui-monospace,monospace;letter-spacing:.04em}#save-status{color:var(--mint);text-align:right}#save-status[data-status=error],#save-status[data-status=conflict]{color:var(--warning)}textarea{display:block;width:100%;height:330px;background:transparent;color:var(--ink);border:0;padding:26px 24px;resize:vertical;min-height:220px;line-height:1.65;font-size:17px;border-radius:0;outline-offset:-3px}textarea:focus-visible{outline:1px solid var(--mint)}textarea::placeholder{color:#7e9588}textarea:read-only{color:var(--muted)}.editor-bottom{display:flex;gap:18px;justify-content:space-between;padding:0 22px 16px;font:10px ui-monospace,monospace;color:var(--muted);overflow-wrap:anywhere}.save-detail{padding:16px 22px 0;border-top:1px solid var(--line);font-size:12px;line-height:1.6;color:var(--muted);margin:0}.toolbar{display:flex;gap:10px;flex-wrap:wrap;padding:18px 22px}.toolbar button,.button,.actions button{font-size:12px;line-height:1.4;border:1px solid #526b5e;background:transparent;color:var(--ink);padding:11px 14px;border-radius:2px;text-decoration:none;text-align:center}.toolbar button:hover,.actions button:hover{background:#294035}.button-primary{background:var(--mint);border-color:var(--mint);color:var(--bg);margin-left:auto}.button-primary:hover{background:#adf5ce}.fault-control{display:flex;align-items:center;gap:9px;font-size:12px;color:var(--muted);padding:0 22px 22px}.fault-control input{accent-color:var(--mint);width:16px;height:16px}.notice{font-size:12px;line-height:1.6;padding:14px 22px;background:#25382e;color:var(--ink);border-bottom:1px solid var(--line)}.notice-warning{background:#3c3022;border-color:#6e5536;color:#ffdfb2}.notice p{margin:4px 0 12px}.actions{display:flex;gap:8px;flex-wrap:wrap}.actions button{border-color:#907049;color:#ffdfb2}.observations{padding:24px}.observations .eyebrow{margin-bottom:22px}dl{margin:0 0 26px}dl div{padding:11px 0;border-bottom:1px solid var(--line)}dt{font-size:11px;color:var(--muted);margin-bottom:4px}dd{margin:0;font:12px ui-monospace,monospace;line-height:1.5;overflow-wrap:anywhere}.log-heading{display:flex;align-items:center;justify-content:space-between;gap:16px}h2{font-size:12px;font-weight:500;margin:0}.text-button{font-size:11px;background:none;border:0;color:var(--mint);padding:5px}#event-log{list-style:none;padding:0;margin:12px 0 0;max-height:260px;overflow:auto;font:10px ui-monospace,monospace;color:var(--muted)}#event-log li{padding:8px 0;border-top:1px solid var(--line);line-height:1.5;overflow-wrap:anywhere}#event-log time{color:var(--mint);margin-right:7px}footer{display:flex;gap:60px;justify-content:space-between;padding:30px 0 44px;font-size:12px;line-height:1.7;color:var(--muted)}footer p{margin:0;max-width:740px}footer p:last-child{min-width:230px}.single{max-width:820px;margin:auto;padding:70px 0}.single .editor-panel{margin-top:30px}.single h1{font-size:clamp(42px,7vw,64px)}.single .lede{max-width:720px}.callout{border-left:2px solid var(--mint);padding:0 0 0 20px;margin:26px 0;color:var(--muted);line-height:1.7;font-size:14px}.single ul{padding-left:20px;color:var(--muted);font-size:14px;line-height:1.8}.single .toolbar{padding-left:0}.control-status{margin:0;padding:16px 22px;border-top:1px solid var(--line);font-size:12px;color:var(--warning);line-height:1.6}@media(max-width:900px){.workspace{grid-template-columns:1fr}.observations{display:grid;grid-template-columns:1fr 1fr;gap:0 28px}.observations>.eyebrow{grid-column:1/-1}dl{grid-row:2/4;margin:0}.log-heading{align-self:start}#event-log{margin-top:0;max-height:285px}footer{gap:24px;flex-direction:column}}@media(max-width:550px){.shell{width:calc(100% - 32px)}.masthead{padding:23px 0}.edition{display:none}.intro{padding:40px 0 28px}h1{font-size:49px}.lede{font-size:15px}.panel-top{padding:18px 16px;align-items:start;font-size:10px}textarea{padding:20px 16px;font-size:16px;height:310px}.editor-bottom{padding:0 16px 16px;flex-direction:column;gap:6px}.toolbar,.save-detail,.notice{padding-left:16px;padding-right:16px}.button-primary{margin-left:0;width:100%}.fault-control{padding-left:16px;padding-right:16px}.observations{display:block;padding:20px}.observations dl{margin-bottom:24px}#event-log{max-height:240px}.single{padding-top:45px}.actions button{width:100%}}
core.test.mjs

Node tests

188 lines · JavaScriptOpen fileDownload
import test from 'node:test';
import assert from 'node:assert/strict';
import { createDraftController, createPausableTimer, parseDraft, DRAFT_KEY, MAX_TEXT_LENGTH } from './core.mjs';

function memoryStorage() {
  const values = new Map();
  return { getItem: (key) => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: (key) => values.delete(key) };
}
const record = (text = '', revision = 'fixture:1') => JSON.stringify({ version: 1, text, revision, savedAt: 1 });

test('absence and a persisted empty string are distinct', () => {
  const store = memoryStorage();
  const editor = createDraftController(store);
  assert.equal(editor.snapshot().status, 'empty');
  assert.equal(parseDraft(store.getItem(DRAFT_KEY)).kind, 'absent');
  editor.edit('');
  assert.equal(parseDraft(store.getItem(DRAFT_KEY)).kind, 'valid');
  assert.equal(parseDraft(store.getItem(DRAFT_KEY)).record.text, '');
  const reopened = createDraftController(store);
  assert.equal(reopened.snapshot().status, 'saved');
  assert.equal(reopened.snapshot().text, '');
});

test('each input persists immediately; a new document recovers the latest revision', () => {
  const store = memoryStorage();
  const first = createDraftController(store, { writerId: 'first', now: () => 12 });
  first.edit('a');
  first.edit('latest draft');
  const saved = first.snapshot();
  assert.equal(saved.status, 'saved');
  assert.equal(saved.dirty, false);
  assert.equal(saved.revision, 'first:2');
  const reopened = createDraftController(store, { writerId: 'second' });
  assert.equal(reopened.snapshot().text, 'latest draft');
  assert.equal(reopened.snapshot().savedAt, 12);
});

test('invalid JSON, bad schema and future versions cannot be silently overwritten', () => {
  for (const raw of ['{', '[]', '{}', '{"version":2}', record('x'.repeat(MAX_TEXT_LENGTH + 1)), '{"version":1,"text":"x","revision":"bad","savedAt":1}', '{"version":1,"text":"x","revision":"ok:1","savedAt":1,"extra":true}']) {
    const store = memoryStorage();
    store.setItem(DRAFT_KEY, raw);
    const editor = createDraftController(store);
    assert.equal(editor.snapshot().status, 'conflict');
    editor.edit('replacement');
    assert.equal(store.getItem(DRAFT_KEY), raw);
    assert.equal(editor.snapshot().dirty, true);
    editor.chooseStored();
    assert.equal(editor.snapshot().text, 'replacement');
    editor.keepMine();
    assert.equal(editor.snapshot().status, 'saved');
    assert.equal(parseDraft(store.getItem(DRAFT_KEY)).record.text, 'replacement');
  }
});

test('quota failure preserves memory and reports saved only after a successful retry', () => {
  const store = memoryStorage();
  let fail = true;
  const adapter = { getItem: store.getItem, setItem(key, value) {
    if (fail) throw Object.assign(new Error('Full'), { name: 'QuotaExceededError' });
    store.setItem(key, value);
  } };
  const editor = createDraftController(adapter);
  editor.edit('keep this');
  assert.equal(editor.snapshot().status, 'error');
  assert.match(editor.snapshot().error, /QuotaExceededError/);
  assert.equal(editor.snapshot().dirty, true);
  assert.equal(editor.snapshot().text, 'keep this');
  assert.equal(store.getItem(DRAFT_KEY), null);
  fail = false;
  editor.save();
  assert.equal(editor.snapshot().status, 'saved');
  assert.equal(editor.snapshot().dirty, false);
  assert.equal(parseDraft(store.getItem(DRAFT_KEY)).record.text, 'keep this');
});

test('denied reads preserve edited memory, then retry safely when an absent store becomes accessible', () => {
  const store = memoryStorage();
  let denied = true;
  const adapter = { getItem(key) {
    if (denied) throw Object.assign(new Error('Denied'), { name: 'SecurityError' });
    return store.getItem(key);
  }, setItem: store.setItem };
  const editor = createDraftController(adapter);
  assert.equal(editor.snapshot().status, 'error');
  assert.equal(editor.snapshot().dirty, false);
  editor.edit('held in memory');
  assert.equal(editor.snapshot().dirty, true);
  denied = false;
  editor.save();
  assert.equal(editor.snapshot().status, 'saved');
  assert.equal(parseDraft(store.getItem(DRAFT_KEY)).record.text, 'held in memory');
});

test('a successful reconciliation read does not hide a failed write before retry', () => {
  const store = memoryStorage();
  const editor = createDraftController({ getItem: store.getItem, setItem() { throw new Error('Write denied'); } });
  editor.edit('not persisted');
  const message = editor.snapshot().error;
  editor.reconcile();
  assert.equal(editor.snapshot().status, 'error');
  assert.equal(editor.snapshot().error, message);
  assert.equal(editor.snapshot().dirty, true);
});

test('access recovery does not overwrite a previously unreadable existing copy', () => {
  const store = memoryStorage();
  store.setItem(DRAFT_KEY, record('existing'));
  let denied = true;
  const editor = createDraftController({ getItem(key) { if (denied) throw new Error('Denied'); return store.getItem(key); }, setItem: store.setItem });
  editor.edit('new memory');
  denied = false;
  editor.save();
  assert.equal(editor.snapshot().status, 'conflict');
  assert.equal(editor.snapshot().text, 'new memory');
  assert.equal(parseDraft(store.getItem(DRAFT_KEY)).record.text, 'existing');
});

test('stale document cannot overwrite another tab; loading the stored copy is explicit', () => {
  const store = memoryStorage();
  const first = createDraftController(store, { writerId: 'first' });
  first.edit('first revision');
  const second = createDraftController(store, { writerId: 'second' });
  second.edit('second revision');
  first.edit('unsaved local change');
  assert.equal(first.snapshot().status, 'conflict');
  assert.equal(first.snapshot().dirty, true);
  assert.equal(first.snapshot().text, 'unsaved local change');
  assert.equal(parseDraft(store.getItem(DRAFT_KEY)).record.text, 'second revision');
  first.chooseStored();
  assert.equal(first.snapshot().text, 'second revision');
  assert.equal(first.snapshot().dirty, false);
});

test('resumed clean document keeps its in-memory text until an explicit conflict choice', () => {
  const store = memoryStorage();
  const resumed = createDraftController(store, { writerId: 'resumed' });
  resumed.edit('in bfcache');
  const other = createDraftController(store, { writerId: 'other' });
  other.edit('newer stored text');
  resumed.reconcile();
  resumed.reconcile();
  assert.equal(resumed.snapshot().status, 'conflict');
  assert.equal(resumed.snapshot().text, 'in bfcache');
  assert.equal(resumed.snapshot().dirty, false);
  resumed.keepMine();
  assert.equal(parseDraft(store.getItem(DRAFT_KEY)).record.text, 'in bfcache');
  assert.equal(parseDraft(store.getItem(DRAFT_KEY)).record.revision, 'resumed:2');
});

test('external deletion is a conflict; selecting absence explicitly clears the editor', () => {
  const store = memoryStorage();
  const editor = createDraftController(store);
  editor.edit('preserve until choice');
  store.removeItem(DRAFT_KEY);
  editor.reconcile();
  assert.equal(editor.snapshot().conflict.kind, 'absent');
  assert.equal(editor.snapshot().text, 'preserve until choice');
  editor.chooseStored();
  assert.equal(editor.snapshot().text, '');
  assert.equal(editor.snapshot().status, 'empty');
});

test('oversized input stays in memory without replacing the last stored draft', () => {
  const store = memoryStorage();
  const editor = createDraftController(store);
  editor.edit('safe');
  editor.edit('x'.repeat(MAX_TEXT_LENGTH + 1));
  assert.equal(editor.snapshot().status, 'error');
  assert.equal(editor.snapshot().dirty, true);
  assert.equal(parseDraft(store.getItem(DRAFT_KEY)).record.text, 'safe');
});

test('resource start and stop are idempotent across repeated resume events', () => {
  let starts = 0;
  let stops = 0;
  let callback;
  let ticks = 0;
  const timer = createPausableTimer({ startInterval(fn) { callback = fn; return ++starts; }, stopInterval() { stops++; }, tick() { ticks++; } });
  timer.start(); timer.start(); callback();
  assert.equal(starts, 1);
  assert.equal(ticks, 1);
  timer.stop(); timer.stop();
  assert.equal(stops, 1);
  assert.equal(timer.isRunning(), false);
  timer.start(); timer.start(); callback();
  assert.equal(starts, 2);
  assert.equal(ticks, 2);
});
server.mjs

Loopback server

35 lines · JavaScriptOpen fileDownload
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';

const portText = process.argv[2] ?? '4178';
if (!/^\d{1,5}$/.test(portText) || Number(portText) < 1024 || Number(portText) > 65535) {
  throw new TypeError('Choose a numeric port from 1024 through 65535. Default: 4178.');
}
const files = new Map([
  ['index.html', 'text/html; charset=utf-8'], ['away.html', 'text/html; charset=utf-8'],
  ['exit-only.html', 'text/html; charset=utf-8'], ['style.css', 'text/css; charset=utf-8'],
  ['app.mjs', 'text/javascript; charset=utf-8'], ['core.mjs', 'text/javascript; charset=utf-8'],
  ['exit-only.mjs', 'text/javascript; charset=utf-8'], ['server.mjs', 'text/javascript; charset=utf-8'],
  ['core.test.mjs', 'text/javascript; charset=utf-8'], ['README.md', 'text/plain; charset=utf-8'],
]);
const server = createServer(async (request, response) => {
  if (!['GET', 'HEAD'].includes(request.method)) { response.writeHead(405, { Allow: 'GET, HEAD' }); response.end(); return; }
  let pathname;
  try { pathname = decodeURIComponent(new URL(request.url, 'http://127.0.0.1').pathname); }
  catch { response.writeHead(400); response.end('Bad request'); return; }
  const name = pathname === '/' ? 'index.html' : pathname.slice(1);
  if (!files.has(name)) { response.writeHead(404); response.end('Not found'); return; }
  try {
    const body = await readFile(fileURLToPath(new URL(name, import.meta.url)));
    response.writeHead(200, {
      'Content-Type': files.get(name), 'Content-Length': body.length, 'Cache-Control': 'no-cache',
      'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer',
      'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'none'; img-src 'none'; font-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
    });
    response.end(request.method === 'HEAD' ? undefined : body);
  } catch { response.writeHead(500); response.end('Unable to read lab file'); }
});
server.listen(Number(portText), '127.0.0.1', () => {
  process.stdout.write(`Draft recovery lab: http://127.0.0.1:${portText}\nLoopback only. Press Ctrl+C to stop.\n`);
});
away.html

Away page

5 lines · HTMLOpen fileDownload
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>Away from the draft · Recovery lab</title><link rel="stylesheet" href="./style.css"></head>
<body><main class="shell"><div class="single"><p class="eyebrow">A DIFFERENT DOCUMENT</p><h1>You left the editor.</h1><p class="lede">Use your browser’s Back button to return through session history. Then inspect the document ID and <code>pageshow.persisted</code> in the event log.</p><div class="callout">A history return may restore the old document from bfcache or load a new document. The result depends on the browser and this visit. The lab reports what actually happened.</div><ul><li><strong>Same document ID + persisted=true:</strong> the existing document resumed.</li><li><strong>New document ID + persisted=false:</strong> a new document read the stored draft.</li><li>A normal reload also creates a new document. It does not reproduce an operating-system discard.</li></ul><div class="toolbar"><a class="button" href="./index.html">Open a new editor document</a><a class="button" href="./exit-only.html">Open the unload-only control</a></div></div></main></body>
</html>
exit-only.html

Exit-only control HTML

5 lines · HTMLOpen fileDownload
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>Unload-only control · Recovery lab</title><link rel="stylesheet" href="./style.css"><script type="module" src="./exit-only.mjs"></script></head>
<body><main class="shell"><div class="single"><p class="eyebrow">INTENTIONALLY FRAGILE CONTROL</p><h1>Save only<br><em>when leaving?</em></h1><p class="lede">This control attempts a save only inside an <code>unload</code> listener. Typing changes memory, not storage. Its separate storage key cannot replace the main editor’s draft.</p><div class="callout">The browser may suppress <code>unload</code>, and registering it can affect bfcache eligibility. A successful normal navigation in one browser does not make it reliable. Use one control tab at a time.</div><section class="editor-panel"><div class="panel-top"><label for="control-draft">UNLOAD-ONLY DRAFT</label><span>NO INPUT SAVE</span></div><textarea id="control-draft" maxlength="20000" aria-describedby="control-status" placeholder="Type synthetic text, then compare the stored copy in a second control tab or after an actual discard."></textarea><p id="control-status" class="control-status" role="status"></p></section><div class="toolbar"><a class="button" href="./away.html">Leave the control</a><a class="button" href="./index.html">Return to the recovery editor</a></div><p class="save-detail" id="control-document"></p></div></main></body>
</html>
exit-only.mjs

Exit-only control script

23 lines · JavaScriptOpen fileDownload
import { parseDraft } from './core.mjs';

const key = 'beyond-unload:exit-only:v1';
const editor = document.getElementById('control-draft');
const status = document.getElementById('control-status');
const documentId = crypto.randomUUID();
let blocked = false;
try {
  const parsed = parseDraft(localStorage.getItem(key));
  if (parsed.kind === 'invalid') { blocked = true; status.textContent = parsed.reason; }
  else {
    editor.value = parsed.record?.text ?? '';
    status.textContent = parsed.kind === 'valid' ? 'Loaded the earlier stored copy. New input is not saved.' : 'No stored control draft. Input is not saved.';
  }
} catch { blocked = true; status.textContent = 'Local storage unavailable. No save will be attempted.'; }
document.getElementById('control-document').textContent = `Document ${documentId}. wasDiscarded: ${'wasDiscarded' in document ? document.wasDiscarded : 'unsupported'}.`;
editor.addEventListener('input', () => { status.textContent = 'Text exists only in this page until an unload handler successfully runs.'; });
window.addEventListener('unload', () => {
  if (blocked) return;
  try {
    localStorage.setItem(key, JSON.stringify({ version: 1, text: editor.value, revision: `${documentId}:1`, savedAt: Date.now() }));
  } catch { /* The document is leaving; there is no reliable recovery UI here. */ }
});
README.md

Setup, experiments and limitations

156 lines · MarkdownOpen fileDownload
# Draft recovery lab

A dependency-free, synthetic-text example for **Beyond unload: Save Drafts and Restore Pages Safely**.
The main editor saves every input synchronously to localStorage; it never registers `unload`.
The separate `exit-only.html` control intentionally saves only in an unreliable `unload` handler.

## Run locally

Download all ten files into one directory. With Node.js 24 (validation runtime: 24.12.0):

| File | Purpose |
| --- | --- |
| [index.html](./index.html) | Main editor shell |
| [style.css](./style.css) | Shared layout and styles |
| [app.mjs](./app.mjs) | Browser lifecycle, ownership and UI adapter |
| [core.mjs](./core.mjs) | Validated draft persistence and timer rules |
| [away.html](./away.html) | Normal history navigation destination |
| [exit-only.html](./exit-only.html) | Intentionally fragile control shell |
| [exit-only.mjs](./exit-only.mjs) | Control that attempts saving only on unload |
| [server.mjs](./server.mjs) | Loopback-only static server |
| [core.test.mjs](./core.test.mjs) | Deterministic application-rule tests |
| [README.md](./README.md) | Run instructions, contract and manual procedures |

```powershell
node server.mjs
```

Open <http://127.0.0.1:4178>. An optional numeric argument selects another port:

```powershell
node server.mjs 4179
node --test core.test.mjs
```

The server binds only to `127.0.0.1`, serves an explicit filename allowlist, accepts GET/HEAD,
and stores no runtime data. Keep the same origin, including port, when testing recovery.
Do not open the HTML through `file:`: storage and secure-context APIs differ there.

## Contract and limits

- Synthetic text only, at most **20,000 UTF-16 code units** (JavaScript `text.length`).
  Synchronous storage blocks the main thread; this deliberately small bound is not a design for large documents.
- Storage key: `beyond-unload:draft:v1`. Record: `{ version: 1, text, revision, savedAt }`.
  `revision` is a document UUID plus a local counter, not a timestamp ordering scheme.
  The schema rejects corrupt, oversized, unsupported-version and unexpected-field records.
  Invalid records are preserved until the user explicitly selects **Keep my text and save a new revision**.
- **Saved locally** means `setItem` returned successfully. It does not mean an operating-system flush,
  backup, remote sync, permanent retention, immunity to browser eviction, or cross-device availability.
  Other same-origin scripts can read this text. Do not type secrets or real personal information.
- `navigator.locks` provides cooperative exclusive writer ownership **between instances of this main editor**.
  The editor is read-only without ownership; hidden/pagehide pages checkpoint, then release ownership.
  Web Locks does not constrain unrelated scripts, extensions or DevTools. A revision comparison alone
  is not an atomic compare-and-swap. Do not copy this code as a claim of general localStorage transactions.
  Browsers without Web Locks get recovery/download only, with an explicit read-only notice.
- On a revision change, the old in-memory document is preserved, including after bfcache restoration.
  **Load stored draft** explicitly replaces the editor; **Keep my text and save a new revision** explicitly replaces storage.
  Both choices require current writer ownership. A deletion is also a conflict, not an empty saved string.
- A newly loaded document disables native textarea autocomplete and hydrates from the validated model on
  `pageshow` (including the next task, after native history form restoration), only if that document has
  received no user input. This hydration never runs for `persisted=true`; a lifecycle-epoch guard cancels
  delayed hydration after another hide/show. A restored bfcache document keeps its existing DOM.
- Quota/access failures preserve memory. Retry is explicit. The manual Blob download is available independently
  of local storage; downloading does not clear the unsaved status.
- `beforeunload` is attached only while the model has unpersisted text. Browser warnings require prior user
  interaction and can be skipped; this is a warning, never the persistence mechanism.
- `visibilitychange` to hidden is a checkpoint. `pagehide` pauses the example resource timer and releases
  the writer lock. `pageshow` restarts the timer idempotently when visible and reconciles storage without
  loading an old snapshot into the DOM. A real discard does not provide a guaranteed final callback.
- The loopback server uses `Cache-Control: no-cache`, not `no-store`. It does not force bfcache admission.
  Web Locks, warnings, browser policy, tooling and other conditions can affect admission. Inspect actual events.
- No service worker, remote requests, analytics or background monitor. The timer only increments a local counter.

## Reproduce meaningful cases

1. **Fresh document:** type text and observe **Saved locally**. Reload. Text should recover with a new
   document ID. Clear the text, reload, and observe an explicitly saved empty record instead of absence.
2. **Failure/retry:** enable **Simulate a failed local write**, then type. The synthetic adapter throws
   `QuotaExceededError`; text stays visible and **Local storage error** appears. Disable the fault and choose
   **Retry save**. A successful write removes the warning state. This tests the application path, not real quota exhaustion.
   The browser may show a leave warning if you try leaving while text is unpersisted. Cancel it, or download first.
3. **History return:** choose **Leave and come back**, then use browser Back. Record the document ID,
   `pageshow.persisted`, timer and log. `persisted=true` reports a real bfcache restoration; a new ID with
   `persisted=false` reports a fresh load. A pass of one path is not evidence for the other path.
4. **Two-tab conflict:** save `A` in tab A, switch to tab B at the same origin and save `B` there.
   Switch back to A. The editor must retain `A` and show a conflict. Choose one explicit resolution.
   Visible side-by-side tabs cannot both own the writer lock; the second stays read-only until the first hides.
   Retry acquisition using **Retry save** if another visible document still held the lock.
5. **Actual discard (manual, Chrome desktop):** use desktop Chrome outside an embedded browser, keep
   DevTools closed, and record the browser version. Chrome can protect a tab after form interaction or
   content edits even when the editor says **Saved locally**; that application status does not clear
   Chrome's interaction signals. Prepare a fresh document before attempting the discard:

   - Save a unique marker and confirm **Saved locally**, then close the editor tab.
   - Open a new tab with `Ctrl+T` and load the same lab origin. Do not duplicate the old tab or use Back.
     Check that the marker has recovered, but do not type or click the lab controls.
   - Record this new document's ID and `wasDiscarded` value as the **pre-discard baseline**.
     This fresh load only prepares the test; it is not the discard being tested.
   - Open `chrome://discards` in another tab of the **same window**, leaving the lab tab hidden.
     Find **Draft recovery lab · Critical Developer** at the lab URL, record its discard count, and
     select **Urgent Discard**. Confirm that the discard count or lifecycle state changes.
   - Return by selecting the lab tab, without manually reloading. Record `document.wasDiscarded=true`,
     a different document ID from the baseline, `pageshow.persisted=false`, recovered marker and save status.
     A new ID or recovered text alone does not prove a discard.

   If the action has no effect, inspect **Is Discardable → View Reason** (hover to reveal the reasons).
   The manual run first reported `Tab is recently visible`, `Tab has form interactions`, and
   `The user has edited the tab's content`; the fresh-tab preparation above allowed the subsequent discard.
   In current Chromium source, this reason list evaluates **proactive** eligibility, while the manual
   action bypasses the minimum background-time check. The displayed reasons are useful diagnostics,
   not a one-to-one explanation of **Urgent Discard**; recent visibility alone is not conclusive.
   Availability, browser policy and implementation versions can still affect the procedure.
6. **Fragile control:** open `exit-only.html`, enter a unique marker and compare a second control document
   before exiting. The stored copy lacks the new input. A real discard or suppressed unload can lose it;
   a history restoration can retain it in memory without any successful save. Use one control writer at a time;
   it intentionally lacks concurrency protection and uses `beyond-unload:exit-only:v1`.
7. **Timer idempotence:** switch visibility and navigate back repeatedly. The timer runs only while visible
   and does not gain additional intervals after repeated resume handling. Background scheduling can be throttled;
   a tick count is an observation aid, not a performance metric.

## Exported application rules

`core.mjs` exports:

- `parseDraft(raw)`: `{ kind: 'absent' | 'invalid' | 'valid', ... }`.
- `createDraftController(storage, { key?, writerId?, now? })`: `snapshot()`, `edit(text)`, `save()`,
  `reconcile()`, `chooseStored()`, `keepMine()`. A browser adapter must hold the writer lock for edits and
  explicit resolutions. `reconcile` never replaces text; initial construction and `chooseStored` can load it.
- `createPausableTimer({ startInterval?, stopInterval?, tick })`: idempotent `start()`, `stop()`, `isRunning()`.
- `DRAFT_KEY`, `WRITER_LOCK`, `MAX_TEXT_LENGTH`.

`core.test.mjs` tests deterministic application rules. It does **not** test browser event delivery,
bfcache admission, Web Locks scheduling, storage durability, download completion or operating-system discard.

## UI selectors for reproducible inspection

`#draft`, `#save-status`, `#save-detail`, `#document-id`, `#user-agent`, `#visibility`, `#persisted`,
`#discarded`, `#timer-state`, `#ticks`, `#lock-state`, `#event-log`, `#fail-writes`, `#retry-save`,
`#download`, `#go-away`, `#conflict`, `#load-stored`, `#keep-mine`, `#control-draft`, `#control-status`.

There is no simulation of `pagehide`, `pageshow`, discard or bfcache in the UI. The checkbox is explicitly
a synthetic storage-write fault, separate from browser lifecycle observations. Preserve actual browser
results separately from deterministic tests and manual procedures when reporting an experiment.

## Discard procedure references

- [Chrome's lifecycle testing guidance](https://developer.chrome.com/docs/web-platform/page-lifecycle-api#testing_your_app_in_the_frozen_and_discarded_states)
  documents manual discarding and checking `document.wasDiscarded` on the subsequent load.
- [Chromium discard eligibility policy](https://github.com/chromium/chromium/blob/main/chrome/browser/performance_manager/policies/discard_eligibility_policy.cc#L378-L402)
  checks DevTools, form interaction and user-edit protections.
- [Chromium diagnostic reason collection](https://github.com/chromium/chromium/blob/main/chrome/browser/performance_manager/user_tuning/user_tuning_utils.cc#L61-L83)
  uses proactive eligibility; the [manual discard action](https://github.com/chromium/chromium/blob/main/chrome/browser/ui/webui/discards/discards_ui.cc#L460-L470)
  ignores the minimum time in the background. These source references explain the current implementation,
  not the exact build used by a reader.

The successful manual discard checks the main checkpoint-based editor. The separate exit-only control
was not tested under an actual discard; its ordinary navigation result does not establish that comparison.

With Node.js available, run these commands in that directory:

node --test core.test.mjs
node server.mjs

Open the loopback URL printed by the server. Use synthetic text. The draft remains in that browser profile and origin until you replace or clear it; stopping the server does not clear browser storage. Use the same host and port when checking recovery. localhost and 127.0.0.1, or two different ports, do not identify the same storage origin.

Serve the example over HTTP rather than opening its HTML through file:. Access to localStorage can itself fail, and its behavior for local files is not a portable storage contract. The localStorage API.

The ZIP also includes an exit-only control for optional reader experiments. A matched discard comparison with that control is outside the results reported here; the README explains how to investigate it.

Verify the recovery path, not just the callback

The checks must identify what was actually exercised:

CheckEvidence required
New-document recoveryA changed boot identifier and the expected stored text
Local write failureWorking text retained, checkpoint unchanged and no saved status
RetrySuccessful write and warning state cleared
Concurrent editorWriter ownership and an explicit response to a changed revision
bfcache restoreA real history traversal with pageshow.persisted === true
Resource reactivationAt most one active timer after repeated pause/resume paths
Discard recoveryA genuine browser discard followed by a new document and, where supported, document.wasDiscarded

A reload tests new-document initialization. It does not test discard. Dispatching a synthetic pageshow tests a handler. It does not establish that the browser admitted the document to bfcache.

I checked new-document recovery, failed writes and retry, download recovery, and conflicts between cooperating tabs. The controller suite passed 12 tests with Node.js 24.12.0. In desktop Chrome, I also completed the three manual cases: a bfcache return, a restored stale draft resolved against the newer checkpoint, and recovery after an actual discard.

The browser-results JSON preserves the captured observations, and the validation notes give the environment, execution history and procedures. My desktop results are recorded as manual passes; their exact Chrome build, document IDs and raw logs were not archived.

For your own run, retain the browser build, OS and lab revision alongside document IDs, lifecycle flags and the event log. Use a real away-page/Back sequence for bfcache; DevTools’ Back/forward cache panel can diagnose a fresh load instead. The README also covers preparing a discard when Chrome protects an edited form. Repeat the checks on the browsers and devices your product supports.

“Saved locally” and “synced” need different evidence

The lab stops at a browser checkpoint. A networked editor needs another state for server acknowledgment, plus revision checks, failure handling and retries. Clearing a local pending operation should follow the application acknowledgment for the exact version it covers.

sendBeacon() returning true means a request was queued for transfer, not that the server accepted the latest draft. It is useful for small telemetry payloads; it is not a substitute for an acknowledged editing protocol. Beacon semantics.

On a restored authenticated page, revalidate access and current records before enabling sensitive actions. Preserve recoverable text separately from that authorization decision. Avoid replacing the editor DOM or moving keyboard focus merely because a return event occurred; the user may be resuming a precise selection or reading position.

The desktop-pet persistence article examines a different runtime with a related distinction: persisted state can support later recovery without a process running continuously. For a browser editor, the useful boundary is equally concrete: which text was successfully checkpointed, and what decision does the application make when it encounters a newer copy?

I prepared this guide with AI assistance and checked primary sources on October 21, 2026. The accompanying evidence record distinguishes controlled tests, captured browser observations and my manual desktop checks.