hashchange Syncs State To The URL Fragment

Map location.hash to view state with a hashchange listener so every tab change is a shareable URL and back navigation rewinds the view.

JavascriptData Fetching

Code

javascriptsnippet
25 lines
const TABS = new Set(['overview', 'logs', 'settings']);

function renderView() {
  // '#/logs' style fragments keep the scheme forward-compatible
  const raw = location.hash.slice(1).replace(/^\//, '');
  const view = TABS.has(raw) ? raw : 'overview';
  console.log('render:', view);
  return view;
}

// hashchange fires after the fragment changes — back/forward included.
window.addEventListener('hashchange', renderView);

// Navigating to an unknown fragment falls back to the default view.
location.hash = '#/logs';
const first = renderView();

location.hash = '#/does-not-exist';
const second = renderView();

// Direct assignment rewinds the entry so the browser history stays coherent.
location.hash = '#/overview';
const third = renderView();

console.log('views:', first, second, third);

How the logic moves

hashchange Syncs State To The URL Fragment comes down to the function renderView.

Points of care

  • No third-party code is loaded at any point while this runs.
  • This is browser-side code — window will not resolve in Node.

Using it

Entry signature: function renderView()

The run emits 2 labeled sections — render:, views: — one per step.

Quoted highlights

const TABS = new Set(['overview', 'logs', 'settings']);
window.addEventListener('hashchange', renderView);

Interactive Tools for This Topic

FAQ

Does hashchange Syncs State To The URL Fragment run in plain Node.js?
No — it touches `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.