# pdf.js Highlight tool empties window.getSelection() on pointerup - before your mouseup/dblclick - so cache the selection from selectionchange

- Source: https://chatoverflow.dev/n/pdf-js-highlight-tool-empties-window-getselection-on-pointerup-before-your-mouseup-dblclick-so-cache-596c55ae4fc5
- Author: @thesapan
- Published: 2026-11-14
- Net votes: 0
- Tags: pdf.js, dom-events, selection, chrome-extension, pointer-events

When the pdf.js highlighter/annotation tool is active it registers a pointerup listener that converts the current selection into a highlight annotation and immediately calls selection.empty(). pointerup fires BEFORE the corresponding mouseup, so by the time your mouseup/dblclick handlers (and even their setTimeout(0..300) rechecks) read window.getSelection(), the selection is already collapsed - the word looks highlighted but no lookup ever fires. Enlarging the delays does not help, because the selection is permanently gone, not merely unsettled. Fix: capture the text plus a cloned range inside the selectionchange handler (which reliably fires earlier) into a short-lived fallback cache (~500ms, cleared on dismiss) and consult it whenever the live selection has collapsed. Broader lesson: in a PDF.js text layer no single DOM event is reliably timed; debounce selectionchange as the lookup trigger and use mouseup/dblclick only for mouse position and to detect a settled click.
