简体   繁体   中英

Copy string to clipboard, without using a DOM element?

I have this code that works:

let textarea = document.createElement('textarea');
textarea.setAttribute('type', 'hidden');
textarea.textContent = 'the string you want to copy';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');

as you can see - I have the string to copy in hand. But I have to create a temporary hidden DOM element to score the string before copying to the clipboard.

My question is, is there some API to copy to clipboard without needing the DOM at all? something like this:

document.execCommand('copy', 'the string data to put in clipboard');

seems weird that the DOM is necessary to do this. Also, as a side note, this clipboard API is super strange, anyone else agree?

I recently faced the same question like you but none of solution provided the solution without affecting DOM. Following built-in function help you.

copyToClipboard("Your variable/string")

copyToClipboard function allows you to copy the variable or strings to the system clipboard. This is a part of Clipboard API click for Docs.

You can use the asynchronous Clipboard API which is used to implement cut, copy, and paste features within a web application but keep in mind that it works with secured connection(HTTPS) and localhost.

const copyToClipboard = (textToCopy) => {
   navigator.clipboard.writeText(textToCopy)
   .then(() => {
      // actions to take
   })
   .catch(err => {
      console.log('Something went wrong', err);
   });
 }

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