Skip to content

Instantly share code, notes, and snippets.

@Fanoflix
Last active June 22, 2023 09:33
Show Gist options
  • Save Fanoflix/c7145e205b89e165477e334c3d6f4553 to your computer and use it in GitHub Desktop.
Save Fanoflix/c7145e205b89e165477e334c3d6f4553 to your computer and use it in GitHub Desktop.
Method to get highlighted/selection text
const getSelectionText = () => {
const selectionText = window.getSelection()?.toString()
if (selectionText?.length) return selectionText
}
@Fanoflix
Copy link
Author

// Example with 'selectionchange' event listener. It fires when the selection/highlight of a document changes.
document.addEventListener("selectionchange", (e: Event) => {
  console.log(getSelectionText())
})

// Example with 'Ctrl+C' event listener.
document.addEventListener("keydown", (e: KeyboardEvent) => {
  if (!((e.metaKey || e.ctrlKey) && e.key === "c")) return

  console.log(getSelectionText())
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment