简体   繁体   中英

Copy to clipboard without appending textarea

I have the following code for chrome addon's js to copy some certain data to clipboard from a certain webpage(I will write code to get data from the webpage later).

 // 1. Create the button var testButton = document.createElement("button"); testButton.innerHTML = "Copy"; // 2. Append somewhere var btnPos = document.getElementsByClassName("menu-userdetails")[0]; btnPos.appendChild(testButton); // 3. Add event handler testButton.addEventListener ("click", copyToClipboard); function copyToClipboard() { var textArea = document.createElement("textarea"); textArea.value = "test copying"; btnPos.appendChild(textArea); textArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copying text command was ' + msg); } catch (err) { console.log('Oops, unable to copy'); } document.body.removeChild(textArea); } 

In this code I have to append the text area to the webpage(after button click) before copying it. But I don't want the textarea to be shown I want to just copy the data inside the textarea without displaying the textarea.

 textArea.style.height = "0px"; textArea.style.width = "0px"; textArea.style.opacity = "0"; 

Adding this code hides the text area.

But even better solution was already in my code, I just made a little mistake in it. I wrote

 document.body.removeChild(textArea); 

While actually I had to write

 btnPos.removeChild(textArea); 

this removes the text area after copying and its so fast that you can't even see the text area appear and disappear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM