Save and restore the text selection

Here are the functions for saving and restoring the text selection:
// Save the selection
// Return a `Range` instance if there is a selected text
const save = function () {
const selection = window.getSelection();
return selection.rangeCount === 0 ? null : selection.getRangeAt(0);
};
// Restore the selection
// `range` is a `Range` object
const restore = function (range) {
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
};

See also