I’m looking at recreating a legacy add-on, and it means that I need to find a way to read the contents of the clipboard.
I am early in the process, and I came across the following code (link). The author posted a simplified version of the basic code to read in the value of the clipboard at Stack Overflow discussion, that seems relatively simple, and is contains well documented code.
Short version (code follows) is that it creates text box on the background page with a text box element, pastes the clipboard into there, and then reads the contents of the text box, which it assigns to a variable.
I have some questions:
- Will this work in Firefox Quantum?
- If yes, would this be invoked from the background script or a content script?
- What is the best way to pass the variable between the two scripts?
I would note that I am working from a position of fairly profound ignorance here, so if I seem clueless, it is because I AM clueless.
Code follows:
bg = chrome.extension.getBackgroundPage(); // get the background page
bg.document.body.innerHTML= ""; // clear the background page
// add a DIV, contentEditable=true, to accept the paste action
var helperdiv = bg.document.createElement("div");
document.body.appendChild(helperdiv);
helperdiv.contentEditable = true;
// focus the helper div's content
var range = document.createRange();
range.selectNode(helperdiv);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
helperdiv.focus();
// trigger the paste action
bg.document.execCommand("Paste");
// read the clipboard contents from the helperdiv
var clipboardContents = helperdiv.innerHTML;