This is how to copy text to clipboard with JavaScript. Or use the @compactjs/clipboard npm module. ✌

You first need to select text:

inputElement.select();

Then you can copy it with:

document.execCommand('copy');

Copying text does only work when following a user action, like a button press.

If you want to copy text without being visible to the user, we need to create an input field to copy from:

const inputElement = document.createElement('textarea');

Fix its position to prevent the window from scrolling:

inputElement.style = 'position:fixed;top:0;left:0;';

Then we can add the text we want to copy:

inputElement.value = 'Awesome text!';

To copy the text we need to append it somewhere to the DOM:

document.body.appendChild(inputElement);

Now just copy the text like shown above and afterwards we can just remove it again:

document.body.removeChild(inputElement);

To make things easier, I made a quick JavaScript module called @compactjs/clipboard.

So, using npm, it’s as easy as this:

npm install @compactjs/clipboard
import { clipboard } from '@compactjs/clipboard';

document
  .getElementById('copy-string')
  .addEventListener('click', () =>
    clipboard('This text is going to be copied.')
  );

Source code: GitHub

Remember: It needs to follow a user action to work!