How can I capture text that’s highlighted in a Google Docs document?

I’m developing a Chrome extension and need to retrieve text that a user has highlighted within a Google Docs file. Unfortunately, the usual method using window.getSelection() does not seem to work in this environment, even though it functions normally in other web pages. Has anyone discovered a reliable alternative or a workaround for this issue?

function fetchHighlightedContent() {
  const selectionFragment = window.getSelection();
  return selectionFragment ? selectionFragment.toString() : '';
}
console.log(fetchHighlightedContent());

Working around this limitation required an unconventional approach. I discovered that the standard window.getSelection() often returns an empty or incomplete result in Google Docs. My solution was to detect selection changes by monitoring mouse events and then accessing Google Docs’ internal formatting APIs to extract highlighted text. This involved some reverse engineering and keeping up with frequent updates from Google, so the solution isn’t stable long term. It demands careful testing and may need readjustment when Docs updates its structure.

After struggling with this issue for a while, I attempted a more indirect approach. In my experiments, I found that tracking user interactions like mousedown and mouseup events proved to be more reliable than relying solely on window.getSelection. By monitoring these events, I was able to derive selection boundaries more consistently by directly interacting with the underlying document structure of Google Docs. This method wasn’t perfect as it required careful listening to mouse events and occasionally adjusting the code to respond to Docs’ internal changes, but it has served me better than using the standard API.

hey, i figured out a workaround by hooking into the docs’ on-change events. instead of relying on window.getSelection(), i read the live node content updates. not 100% reliable but it caught most of the highlighted text for my needs.