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'