All guides

JavaScript · URL · State

How to save an interactive demo’s state in a URL

Author: Grundy · Checked: November 13, 2026

A link to an algorithm page explains where to look, but may not reproduce what its author saw. The array, graph, maze or playback position can be different. On Grundyjs, sharing therefore captures a specific example. We will examine the sorting player, weighted maze and text-maze constructor, compare representations of the same state and follow a real change from format version 1 to version 2.

1. Decide what the recipient should recover

For insertion sort, the saved state contains the original array, algorithm name, playback position and speed. A snapshot is this set of saved values. In the example, algorithm names the algorithm, data.values holds its input, position: 1300 means 1300 milliseconds into the animation, and speed: 1 means normal speed. The player rebuilds the algorithm steps and opens paused. An unsubmitted input draft, timers and the picture drawn on the canvas are not saved. The format version tells the application how to read these fields. Reproducing the same animation also depends on keeping compatible algorithm and playback code.

{
  "algorithm": "insertion-sort",
  "data": { "values": [5, 2, 4, 2, 1] },
  "position": 1300,
  "speed": 1
}

2. Separate data, encoding and storage location

Choose both how to write the data and where to put it. JSON records objects and arrays as text. To include it in a URL, special characters can be replaced with codes such as %7B for {; this is percent-encoding. Another option is Base64URL, which represents bytes using characters suitable for URLs. A query is the parameter part after ?, for example ?speed=2. A fragment is the part after #, for example #player-v1=…. A larger snapshot can instead live on a server, with its identifier in the URL. The table compares these choices. Its teaching formats do not add new formats to the existing sorting player.

Ways to represent and locate shared state
VariantUseful forTradeoff
?v=1&values=…A few editable settingsDefine how arrays and nested objects are written
#demo-v1=%7B…%7DJSON with familiar field namesReplacing special characters adds length; lab format
#player-v1=ey…The general player state structureNeeds a decoder; no compression
seed + parametersRebuilding a repeatable sceneDepends on generator behavior
/snapshot/<id>/Large payloads stored on a serverRequires storage; proposed option

3. Readable parameters: start with URLSearchParams

Parameters are convenient for a few settings. URLSearchParams handles special characters when building the URL. On reading, check that required parameters exist, occur only once and contain allowed values. Check an empty value before converting it to a number: Number(null) and Number("") both return zero. When requesting a page, the browser sends the query to the server but leaves out the fragment. Scripts on the page can still read both parts, so shared URLs should not contain secrets. The code below uses an illustrative path; /play/example/ is not a working page on this site.

const url = new URL("/play/example/", window.location.origin);
url.searchParams.set("v", "1");
url.searchParams.set("values", [5, 2, 4, 2, 1].join(","));
url.searchParams.set("position", "1300");
url.searchParams.set("speed", "1");
console.log(url.href);

4. The sorting player: JSON inside #player-v1

The general player state structure contains algorithm, data, position and speed. The player turns this object into JSON, converts the text to UTF-8 bytes and writes those bytes as Base64URL, omitting trailing = characters. The link points to /play/insertion-sort/ or its English equivalent. A reader is the code that reads and checks a saved link. The common reader checks the #player-v1= prefix, algorithm, position and supported speeds. SortingPlayer then checks the array and whether the requested position fits the recalculated animation. The limit of 150,000 characters in player-link.ts is an application limit; a messenger may accept less. Base64URL can be decoded by anyone and does not compress the data.

// Existing site module: data/player-link.ts
import { playerHash, readPlayerHash } from "@/data/player-link";

const snapshot = {
  algorithm: "insertion-sort",
  data: { values: [5, 2, 4, 2, 1] },
  position: 1300,
  speed: 1,
};
const url = new URL("/play/insertion-sort/", window.location.origin);
url.hash = playerHash(snapshot);

// The general player state structure is checked here. Algorithm-specific data and the
// actual timeline duration still need validation before restoration.
const state = readPlayerHash(url.hash, "insertion-sort");

5. Encode Unicode through bytes

Unicode covers characters from different writing systems and emoji; UTF-8 is a way to represent them as bytes. Calling btoa(JSON.stringify(value)) directly can fail on Cyrillic text. TextEncoder first converts the text to UTF-8 bytes. An encoder turns data into an encoded string; a decoder recovers data from it. The example below rejects invalid UTF-8 and limits the encoded input to 4096 characters. Its return type is unknown because JSON.parse alone cannot prove that the required fields and values are present. The lab uses the site’s existing encoder and reader for its Base64URL option.

function encodeJson(value: unknown): string {
  const bytes = new TextEncoder().encode(JSON.stringify(value));
  const binary = Array.from(bytes, byte => String.fromCharCode(byte)).join("");
  return btoa(binary)
    .replaceAll("+", "-")
    .replaceAll("/", "_")
    .replace(/=+$/, "");
}

function decodeJson(encoded: string): unknown {
  if (encoded.length > 4096 || !/^[A-Za-z0-9_-]+$/.test(encoded)) {
    throw Error("Invalid payload");
  }
  const binary = atob(encoded.replaceAll("-", "+").replaceAll("_", "/"));
  const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
  return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
}

const restored = decodeJson(encodeJson({ text: "Привет, лабиринт!" }));

6. Change the representation and restore the state

Encode the supplied array, then switch between the three formats. Compare the character counts: Base64URL need not be the shortest option. With URL parameters selected, change speed=1 to speed=2 in the text field and restore the state. Try an unsupported speed or repeat the position parameter: the last valid state should remain. The link at the bottom always opens the actual player using #player-v1, regardless of which teaching format is selected.

Characters in this representation: 126

{
  "algorithm": "insertion-sort",
  "data": {
    "values": [
      5,
      2,
      4,
      2,
      1
    ]
  },
  "position": 1300,
  "speed": 1
}
Open saved state in the sorting player

The actual player link always uses #player-v1. The two teaching formats work only in this lab. Editing the text does not apply it until you restore. This lab does not change the article URL.

7. A seed is a recipe, not a complete snapshot

A seed is the starting number for a pseudorandom generator: the same seed can reproduce the same sequence of choices. A maze can be rebuilt from its dimensions and seed while the generator, algorithm and neighbour order stay the same. Imported walls cannot generally be recovered this way. The weighted-maze comparison therefore uses #maze-v1 with the actual walls, cell costs, start and finish, visible search methods, playback position and speed. It also saves whether to display the history and the frontier — cells discovered but not yet processed. Here index counts playback waves, groups of cells shown together. Sorting’s position uses milliseconds instead.

8. Changing the format: text maze maze=1 → maze=2

The text-maze constructor has a reader for both maze=1 and maze=2. Its writer — the code that creates new links — now writes maze=2. Version 1 stores text, font, frame layout, detail, seed, duration and search methods. Those settings cannot guarantee that another device will draw the letters identically. Version 2 adds shape, the already-built lettering mask: a grid marking which cells belong to the letters. It can replay and export that shape without the original font file. Changing the text, layout or detail requires a font and rebuilding. Old version 1 links still open, with a warning that the exact lettering shape was not saved.

9. Change packing without changing the meaning

The shape field supports two ways to store the same mask. With r., consecutive equal cells are recorded as a value and run length; this is run-length encoding, or RLE. With b., each cell takes one bit, so eight cells fit in a byte. The encoder compares their binary sizes and chooses the smaller one. A checksum is a number calculated from the mask and its settings; a mismatch helps detect damaged or inconsistent data, but does not prove authorship. The decoder checks dimensions and input length before allocating memory. For larger data, consider compression, file export or server storage. Compressed data also needs a limit on its expanded size.

10. Keep old readers and write the new version

A format defines field names, allowed values and their meaning. An optional field with a default may fit the existing version, but older readers can reject extra fields. Renaming position, changing its units or requiring a new field calls for a new version. Keep readers for supported versions, check the data, then convert it to one structure used by the application. New links use the latest format. Unknown versions should show an error. In the example, readers.v1 and readers.v2 are supplied functions that already validate their own formats. The conversion renames position to timeMs while keeping milliseconds. This illustrates a possible change; it does not add player-v2 support to the site.

// Teaching example: these readers validate their respective schema.
// This does not add #example-v2 support to the site's players.
type Current = { timeMs: number; speed: number };
type Readers = {
  v1: (payload: string) => { position: number; speed: number };
  v2: (payload: string) => Current;
};

function readVersioned(hash: string, readers: Readers): Current {
  if (hash.length > 4096) throw Error("Link too long");
  if (hash.startsWith("#example-v1=")) {
    const old = readers.v1(hash.slice("#example-v1=".length));
    return { timeMs: old.position, speed: old.speed };
  }
  if (hash.startsWith("#example-v2=")) {
    return readers.v2(hash.slice("#example-v2=".length));
  }
  throw Error("Unsupported link version");
}

11. Validate and prepare before replacing the scene

First limit the string length and recognize its version. Decode the data, check types, allowed values and memory limits, recalculate the algorithm steps and verify the requested position. Only then replace the current scene and leave playback paused. A TypeScript type assertion does not check data at runtime. The maze player prepares the restored state separately and releases its resources on failure or cancellation. The usePlayerLink hook cancels the previous restore when another fragment arrives. It listens for hashchange, the browser event for a changed fragment. An absent state and a damaged state need different handling.

12. A Share button or a continuously updated URL?

The player creates a link when Share is requested. The recipient gets a chosen position on pause. An editor may instead update the address after a meaningful change. replaceState replaces the current browser history entry; pushState adds another entry that Back can return to. Decide how Back and Forward restore state and avoid writing on every animation frame. Calling replaceState does not trigger hashchange, so the application must update its state directly too.

13. What a share link does not promise

The constructor saves the lettering mask, but not local font or music files. A redirect sends a visitor to another URL: the current /y/ and /r/ links lead to pages rather than saved player states. A service that stores snapshots would need rules for retention, access and deletion. A link carrying all its own data still needs a working page and compatible reader. Test links in the places where people will copy and send them, and leave confidential data out of shared URLs.

14. What to verify before sharing

Save and restore examples with repeated numbers, negative values and boundary values; compare the recovered state with the original. Check rejection of damaged strings, unknown versions, duplicate required parameters, unsupported speeds, oversized arrays and positions beyond the animation. Keep fixed examples of old links alongside tests of newly created ones. Try a fresh tab, the English page, a second restore and an error after valid data. When changing formats, check that the same input and playback settings are recovered. If an old link never contained the lettering mask, explain that limit.