How to extract highlighted text from Google Docs embedded viewer

I’m working on a web application that displays Word documents using Google’s document viewer inside an iframe. Users can view and modify these documents directly in the embedded viewer.

My challenge is that I need to capture any text that users select within the Google Docs iframe and automatically transfer it to an input field that exists outside the iframe on my main webpage.

Is there a way to access selected content from the embedded Google Docs viewer? I’ve been struggling with cross-frame communication.

As a bonus feature, I’d love to be able to modify the highlight color of the selected text programmatically.

Any suggestions or code examples would be really helpful. Thanks!

Unfortunately, this won’t work because of browser security restrictions. Google Docs embedded viewer runs in a sandboxed iframe with strict cross-origin policies - you can’t access its content or DOM elements from outside JavaScript. No way to capture text selections or change highlight colors from your main page. I ran into this exact problem building a document annotation system last year. The embedded viewer’s basically a black box. It doesn’t expose selection events and won’t let you manipulate anything externally. PostMessage won’t help either since Google doesn’t provide hooks for selection data. Best alternative? Build a custom document viewer using something like PDF.js for PDFs, or convert Word docs to HTML first. You’ll have full control over selections and styling, but it’s way more work than just dropping in an iframe.

Yeah, cross-frame limitations are exactly what’s blocking you here. I spent months fighting similar restrictions when I built a collaborative document platform. Google’s viewer runs in their security sandbox, so external scripts can’t access selection events or mess with the document directly. But there’s a workaround if you control the document source. Try using Google Docs API to embed documents as editable content instead of the standard viewer iframe. You’ll need to set up authentication, but it gives you way more control over document interactions. Another option I’ve seen work is building a browser extension that bridges your app and the embedded viewer. Extensions run with elevated permissions and can capture selections across different origins. Downside is users have to install your extension. For highlights specifically, you’d need to work with Google Docs suggestions or comments API instead of direct text manipulation. It’s more complex but plays nice with their security model while getting you similar visual results.