Listening for Bookmark Changes

Keep an extension in sync with the user's bookmarks: onCreated, onChanged, onMoved, onRemoved and reorder events, ignoring import storms, debouncing bulk edits, and reconciling after the worker sleeps.

Published October 2, 2026 Updated October 2, 2026 7 min read
Table of Contents

The extension keeps its own copy of the user’s bookmarks — a search index, a tag database, a mirror on your server. It reads the tree once at install and then listens for changes. Within a week the copy has drifted: a folder moved in the bookmark manager, an import from another browser fired three thousand events in two seconds, a sync from another device renamed items while the service worker was asleep. Bookmark events are reliable individually and treacherous in aggregate. This guide builds a listener that keeps a derived copy correct. It belongs to browser data APIs for bookmarks, history and downloads.

The event model

chrome.bookmarks fires onCreated(id, node), onRemoved(id, { parentId, index, node }), onChanged(id, { title, url }), onMoved(id, { parentId, index, oldParentId, oldIndex }) and onChildrenReordered(id, { childIds }). Chrome also fires onImportBegan and onImportEnded around imports, during which it emits a creation event for every imported node. Removing a folder fires a single onRemoved for the folder — not one per descendant — with the removed subtree in node (Chrome 48+). Changes that arrive via browser sync from other devices fire the same events. Each event wakes an evicted service worker, so a large edit is also a burst of wake-ups.

An import storm and how to absorb itonImportBegan arrives, then thousands of onCreated events which the worker ignores except for setting a dirty flag, then onImportEnded triggers a single full re-read of the tree.BrowserService workerDerived indexonImportBeganimporting = trueonCreated × 3,000ignoredonImportEndedgetTree()rebuild once
During an import, events are noise; the tree after the import is the signal.

Step-by-step: a listener that stays correct

1. Register every event at the top level

 1// sw.js
 2const handlers = {
 3  onCreated: (id, node) => apply({ op: "upsert", node }),
 4  onChanged: (id, info) => apply({ op: "patch", id, info }),
 5  onMoved: (id, info) => apply({ op: "move", id, info }),
 6  onRemoved: (id, info) => apply({ op: "remove", id, subtree: info.node }),
 7  onChildrenReordered: (id) => apply({ op: "reorder", id }),
 8};
 9for (const [event, fn] of Object.entries(handlers)) chrome.bookmarks[event].addListener(fn);
10
11chrome.bookmarks.onImportBegan?.addListener(() => setImporting(true));
12chrome.bookmarks.onImportEnded?.addListener(() => { setImporting(false); scheduleFullResync(); });

Execution context: the service worker. Every bookmark event can wake the worker, so every listener must exist after the first synchronous pass. The import events are optional-chained because Firefox does not implement them. The bookmarks permission produces a “Read and change your bookmarks” install warning.

2. Skip work during imports

1async function setImporting(flag) {
2  await chrome.storage.session.set({ bookmarksImporting: flag });
3}
4
5async function apply(change) {
6  const { bookmarksImporting } = await chrome.storage.session.get("bookmarksImporting");
7  if (bookmarksImporting) return markDirty();                 // full resync at the end
8  enqueue(change);
9}

Execution context: the service worker. Storing the importing flag in chrome.storage.session rather than a variable keeps it correct if the worker is evicted mid-import — imports can take longer than thirty seconds and the worker may be restarted between batches of events. Applying thousands of incremental updates during an import is slow and pointless when one tree read at the end produces the same result.

3. Batch incremental changes

 1let queue = [];
 2let flushTimer = null;
 3
 4function enqueue(change) {
 5  queue.push(change);
 6  clearTimeout(flushTimer);
 7  flushTimer = setTimeout(flush, 300);
 8}
 9
10async function flush() {
11  const batch = queue; queue = [];
12  if (batch.length > 200) return scheduleFullResync();        // cheaper to re-read
13  const { bmIndex = {} } = await chrome.storage.local.get("bmIndex");
14  for (const c of batch) applyToIndex(bmIndex, c);
15  await chrome.storage.local.set({ bmIndex, bmIndexAt: Date.now() });
16}

Execution context: the service worker. A user dragging forty bookmarks into a folder produces forty onMoved events in a fraction of a second; one storage write per burst instead of forty keeps the worker responsive. The pending events keep the worker alive long enough for a 300-millisecond timer. Above a threshold, a full resync is simpler and faster than replaying each change.

Bookmark events and how to apply themEach bookmark event, what it carries, and how a derived index should apply it, including the folder removal and reorder cases.EventCarriesApply asonCreatedFull nodeUpsertonChangedtitle, urlPatch fieldsonMovedNew and old parent/indexUpdate pathonRemoved (folder)Removed subtreeDelete all descendantsonChildrenReorderedchildIdsRe-read that folder
Folder removals carry the subtree; reorders carry only child ids.

4. Handle folder removals recursively

 1function applyToIndex(index, c) {
 2  switch (c.op) {
 3    case "upsert": index[c.node.id] = pick(c.node); break;
 4    case "patch":  index[c.id] = { ...index[c.id], ...c.info }; break;
 5    case "move":   if (index[c.id]) index[c.id].parentId = c.info.parentId; break;
 6    case "remove": for (const id of collectIds(c.subtree)) delete index[id]; break;
 7  }
 8}
 9
10function collectIds(node, out = []) {
11  if (!node) return out;
12  out.push(node.id);
13  for (const child of node.children ?? []) collectIds(child, out);
14  return out;
15}

Execution context: the service worker. Removing a folder with five hundred bookmarks fires one event; an index that only deletes the folder’s own id keeps five hundred orphans. Walking the provided subtree removes them all. Paths derived from parents — “Work / Projects / Q3” — must also be recomputed for descendants of a moved folder; storing only parentId and computing paths on read avoids that update storm.

5. Reconcile on startup

1chrome.runtime.onStartup.addListener(scheduleFullResync);
2chrome.runtime.onInstalled.addListener(scheduleFullResync);
3
4async function scheduleFullResync() {
5  const tree = await chrome.bookmarks.getTree();
6  const bmIndex = {};
7  (function walk(n) { if (n.url) bmIndex[n.id] = pick(n); n.children?.forEach(walk); })(tree[0]);
8  await chrome.storage.local.set({ bmIndex, bmIndexAt: Date.now() });
9}

Execution context: the service worker. Events are not delivered while the browser is closed, and sync may apply many changes during startup before your listeners are ready. A full rebuild at startup — fast for typical trees of a few thousand items — makes the derived index self-healing. For very large trees, compare a cheap fingerprint (count plus newest dateAdded) before deciding to rebuild.

Three paths into the derived indexSmall bursts of events are applied incrementally, large bursts and imports trigger a full rebuild, and startup always triggers a rebuild, all writing one index to storage.≤ 200 eventsdebounced batch> 200 or importtoo many to replayonStartupmissed while closedapply or rebuildapplyToIndexincrementalgetTree() rebuildfullbmIndexstorage.local
Incremental for the common case, rebuild for everything unusual.

6. Push changes to your server in batches

If the derived copy is mirrored to a backend, do not send one request per event. Append changed ids to an outbox in storage, and flush it on a short alarm or when the burst settles; the server receives a compact set of upserts and deletions.

1async function recordForUpload(ids, kind) {
2  const { bmOutbox = { upsert: [], remove: [] } } = await chrome.storage.local.get("bmOutbox");
3  bmOutbox[kind] = [...new Set([...bmOutbox[kind], ...ids])];
4  await chrome.storage.local.set({ bmOutbox });
5}

Execution context: the service worker. Deduplicating ids in the outbox collapses repeated edits of the same bookmark into one upload, and a removal recorded after an upsert should drop the id from the upsert list. The durable outbox pattern, with retries and conflict handling, is covered in syncing extension data with a backend API. Bookmarks reveal a great deal about a person; upload them only with explicit consent and say so in the listing.

Common mistakes

  • Applying every import event. Thousands of writes in seconds; wait for onImportEnded.
  • Treating folder removal as one item. Descendants become orphans in your index.
  • Storing full paths. A folder rename invalidates every descendant’s path; store parent ids.
  • No startup reconciliation. Changes made while the browser was closed or by sync at startup are missed.
  • Listening in a popup. The popup closes; only the worker sees every change.

Cross-browser variation

  • Chrome / Edge: all events including import begin/end; onRemoved includes the removed subtree.
  • Firefox: supports create, remove, change, move and reorder events; no import events. Separators are bookmark nodes with type: "separator".
  • Safari: the bookmarks API is not available to Safari web extensions. Feature-detect and disable bookmark-based features.

Verification

  1. Create, rename, move and delete a bookmark; after each, compare bmIndex with chrome.bookmarks.getTree().
  2. Delete a folder containing many bookmarks and confirm none remain in the index.
  3. Import bookmarks from an HTML file via the bookmark manager and confirm exactly one rebuild happens.
  4. Close the browser, change bookmarks on another synced device, reopen, and confirm the index matches after startup.

FAQ

Do bookmark events fire for changes from sync?

Yes, they arrive like local changes, often in bursts at startup or when sync resumes.

Can I tell whether a change came from the user or from sync?

Not from the event. If it matters, compare against your last known state.

How large can the tree be?

Heavy users have tens of thousands of bookmarks. getTree remains fast, but avoid writing the whole index to chrome.storage.sync.

Other Core APIs & Cross-Browser Data Management Resources