Need to highlight and copy text from google doc viewer to clipboard

1k views Asked by At

I have to create a process where a document is shown to the user and the user can highlight text and copy (and eventually paste) the text from some portions of the document.

I am using google doc viewer in an iframe (since I need a universal doc viewer that's free - although I'm open to other ideas on viewers). Google doc viewer does what I need but it seems that I don't have access to the internals of the iframe to get the highlighted contents.

I've looked at many links related to triggering a copy (cntl-c) in javascript, but nothing firm in the process.

Ideally I would like a button outside of the iframe to click on which would copy to the clipboard the selection a user made inside of the google doc viewer.

Any suggestion on how to achieve this?

2

There are 2 answers

0
mn. On
0
Abreham On

For anyone looking for the answer. You can get the selected text inside docs-texteventtarget-iframe .

const iframe = document.querySelector(".docs-texteventtarget-iframe")
const selectedText = iframe.contentDocument.getSelection().toString()
console.log(selectedText)

WARNING: The catch is that it doesn't work in Windows and Mac Chrome for some reason. It only works in ubuntu chrome so far.