Skip to content

Home

How can I get the currently selected text in the browser?

When working with text in the browser, you may need to get the currently selected text to perform various operations. This can be useful for implementing features like copy-paste functionality, text highlighting, or custom context menus.

As usual, JavaScript provides a way to achieve this using Window.getSelection(), which returns a Selection object representing the text currently selected in the document. You can then use Selection.toString() to get the actual text content.

const getSelectedText = () => window.getSelection().toString();

getSelectedText(); // 'Lorem ipsum'
💬 Note

A more advanced use case of this functionality can be found in the copy text to clipboard snippet, used to select and copy text to the clipboard.

More like this

Start typing a keyphrase to see matching snippets.