Writing a tiny browser extension in Chrome to copy certain text from certain web pages to the clipboard. HTML format so that people can embed it in office programs such as word, appearance, etc.
document.execCommand('copy')- this is the command I use, it is launched by the key combination document.onkeydown(Alt + 1), and it works fine - but only for the first time. If you try to press the key combination again, it will do nothing.
I found the reason for this, document.queryCommandEnabled("copy")returning true for the first time and false for any additional attempt. If I reload the page, it returns true again. In addition, if I clicked outside the browser window after loading the page, and then clicked in the browser and used a key combination, false is returned immediately, even for the first time.
function copy(text) {
var sel = document.createElement("div");
sel.style.opacity = 0; sel.style.position = "absolute";
sel.style.pointerEvents = "none"; sel.style.zIndex = -1;
sel.innerHTML = text;
document.body.appendChild(sel);
var range = document.createRange();
range.selectNode(sel);
window.getSelection().addRange(range);
alert("Enabled = " + document.queryCommandEnabled("copy") + " Design mode = " + document.designMode);
try {
document.execCommand('copy');
}
catch (err) {
alert('Unable to copy');
console.log('Unable to copy');
}
document.body.removeChild(sel);
}
document.onkeydown=function(e){
if(e.altKey && e.which == 49) {
copy(link_variable);
return false;
}
}
Any ideas?
Adding a manifest file:
{
"manifest_version": 2,
"name": "Usage text",
"version": "0.2",
"description": "Whatever",
"content_scripts": [
{
"matches": [
"*://some.specific.site.com/*"
],
"js": ["content.js"]
}
],
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"name": "Whatever",
"default_icon": "icon.png"
},
"permissions": [
"tabs",
"clipboardWrite"
]
}
Update:
Transfer the operation from the script content to the background script unchanged.