When it is impossible to programmatically copy selected text

getSelection() does not always return the text value or coordinates of the entire selection

Marian C.
4 min readOct 27, 2024

Typically getSelection() is used for placing programmatically the selected text to the clipboard. It can also be used for decorating the selected Range using the Custom Highlight API. But it seems that it is not always possible to accurately retrieve the selection.

Retrieving text value of the selection

The selected text is returned by toString() of a Selection object that can be obtained with either document.getSelection() or window.getSelection(). Both methods return the same object:

Let’s explore possible string values of the Selection objects using a sample page that has a selectionchange event listener:

// main.js

document.addEventListener("selectionchange", onSelectionChange);

function onSelectionChange() {
console.log(getSelection().toString());
}

selectionchange event is fired when the selection changes, and so the listener prints values of distinct selections…

--

--

Marian C.
Marian C.

Written by Marian C.

Java, JavaScript and SQL developer. Interested in data collection and visualization.

Responses (20)