I'm trying to create a small bookmarklet which will allow teachers to highlight text on a webpage and download that selection as a plain text (.txt) file. I have a demo page set up to show what I have working and where I'm stuck.
On the demo page, I can highlight text and download it directly using the "Download Selection" button. But, if you mis-highlight, you have to go back and do it again. The "Make Page" button grabs the highlighted text and creates a popup with the text for proofing.
script.js
function makePage(text) {
var text = "";
if(typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
var newPage = window.open("", null, "height=200,width=300,status=yes,menubar=no");
newPage.document.write("<body><a id='download' download='text.txt'></a><p id='copy'>" + text + "</p><button id='download' onclick='getPlainText()'>Download</button><scipt type='text/javascript' src='script.js' defer></script></body></html>");
console.log(text)
}
}
function getPlainText(copy) {
var text = "";
if(typeof window.getSelection != "undefined") {
text = window.getElementById('copy').innerContent;
var download = document.getElementById('download');
download.href = 'data:text/plain;charset:utf-8,' + encodeURIComponent(text);
var event = new MouseEvent('click');
download.dispatchEvent(event);
}
return text;
}
When I click the Download button on the popup, I get a TypeError in the console:
Uncaught TypeError: window.getElementById is not a function
I've moved the script in the document, but regardless of where it is, the error returns and I can't figure out why. Any ideas on how to get that to work?