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>
Edit:
Using PDFjs instead of the Chrome default pdf viewer, the code works. A quick way to get PDFjs running can be found here.