0

I have a simple HTML page with a button, and an iframe displaying a PDF file. When the button is clicked, I need to get the selected text in the PDF if any, and store it in a variable.

So far I have tried options from this question, among others. However it seems that getSelection.toString() is always returning an empty string.

By the way I am using Chrome with its default PDF viewer. Is there a way to achieve the above?

My code so far:

$(document).ready(function() {

  $("#btn-get-selection").on("click", function(e) {
    var iframe = document.getElementById('iframe');
    var idoc = iframe.contentDocument || iframe.contentWindow.document;
    var text = idoc.getSelection().toString();

    //always getting empty string
    console.log(text);
  })
});
<button id="btn-get-selection" class="btn btn-primary">Get Selection</button>

<iframe id="iframe" src="sample.pdf" width="100%" height="500" frameborder="0"></iframe>

Current output: Current output


Edit:

Using PDFjs instead of the Chrome default pdf viewer, the code works. A quick way to get PDFjs running can be found here.

Anis R.
  • 6,656
  • 2
  • 15
  • 37
  • Can you try `var iframe = document.querySelector('iframe');`? – DreamBold Dec 20 '22 at 21:01
  • https://codepen.io/dreambold/pen/yLqyaJG?editors=1111 It's working here – DreamBold Dec 20 '22 at 21:07
  • Does this work? `var iframe = document.getElementById('iframe'); var iwin = iframe.contentWindow; var idoc = win.document; var text = (iwin.getSelection) ? iwin.getSelection().toString() : (idoc.selection && idoc.selection.createRange) ? idoc.selection.createRange().text : '';` – Peter Thoeny Dec 21 '22 at 00:41
  • @PeterThoeny "Uncaught ReferenceError: win is not defined". If I replace `win` by `iwin`, I get an empty string again. – Anis R. Dec 21 '22 at 13:49
  • Typo on my side, yes I meant `iwin` instead of `win` – Peter Thoeny Dec 21 '22 at 19:39

0 Answers0