Notes:
chrome.browserAction.onClicked.addListener with popup
Chrome Extension get selected text
Window.postMessage()
Capturing ctrl+z key combination in javascript
Related paradigms explanations:
(() => {}
ES6 Arrow Function Is Simple, This Article Just Made It Simpler For JS Beginners
(()
What do parentheses surrounding an object/function/class declaration mean?
return {}
What do curly braces in JavaScript mean?
I'm searching for help on how to correctly understand and rewrite ugly code.
This is a working and tested code I was given:
document.body.appendChild(document.createElement('script')).text = '(' + (() => {
addEventListener('message', function _(e) {
if (e.data && e.data.type === 'getSelectedTextReply') {
removeEventListener('message', _);
alert('SUCCESS:\n' + e.data.selectedText);
}
});
document.getElementById('plugin').postMessage({type: 'getSelectedText'}, '*');
}) + ')()';
Current state of the script, tested and working:
function onKeyboardKeyDown() {
//Checking if Content-Script is inserted inside PDF viewer extension)
if (document.getElementById('plugin')) {
alert('This is a PDF file opened by Chrome PDF viewer');
//After opening a PDF page with Chrome PDF viewer
//Assign a listener to the browser window,
//to listen for a Selected Content by an User
function addTextSelectionListener() {
function receiveMessage(e) {
if (e.data && e.data.type === 'getSelectedTextReply') {
removeEventListener('message', receiveMessage);
alert('SUCCESS:\n' + e.data.selectedText);
}
}
//Setup listener to listen for a message from Chrome PDF viewer API
window.addEventListener('message', receiveMessage);
//Send request to get Selected Text from Chrome PDF viewer
document.getElementById('plugin').postMessage({
type: 'getSelectedText'
}, '*');
}
//add Self executable addListener() function to the Script Tag
//before appending it to the PDF viewer
var scriptElement = document.createElement('script');
scriptElement.text = '(' + addTextSelectionListener + ')()';
document.body.appendChild(scriptElement);
} else {
//alert("This is not a PDF file page opened by Chrome PDF viewer");
}
}
document.onkeydown = onKeyboardKeyDown;
Earlier, solved:
This is what I have done yet:
var scriptElement = document.createElement('script'); function listener(){ return { addEventListener('message', function _(e) { if (e.data && e.data.type === 'getSelectedTextReply') { removeEventListener('message', _); alert('SUCCESS:\n' + e.data.selectedText); } }); document.getElementById('plugin').postMessage({type: 'getSelectedText'}, '*'); }; } scriptElement.text = '(' + listener + ')()'; document.body.appendChild(scriptElement);
However, right now it has error:
Uncaught SyntaxError: Unexpected string myscript.js:5
This is the fifth line, where Syntax error occurs:
addEventListener('message', function _(e) {