How to use JavaScript execCommand to copy hidden text to clipboard?

Sometimes, we want to use JavaScript execCommand to copy hidden text to clipboard.

In this article, we’ll look at how to use JavaScript execCommand to copy hidden text to clipboard.

How to use JavaScript execCommand to copy hidden text to clipboard?

To use JavaScript execCommand to copy hidden text to clipboard, we convert it to a text input first.

For instance, we write

<input id="dummy" name="dummy" type="hidden" />

to add a hidden input.

Then we write

const copyText = document.getElementById("dummy");
copyText.type = "text";
copyText.select();
document.execCommand("copy");
copyText.type = "hidden";

to get the hidden input with getElementById.

We then set the type of the input to 'text'.

Next we call select to select the text inside.

Then we call execCommand with 'copy' to copy the selected text into the clipboard.

And finally we set its type back to 'hidden'.

Conclusion

To use JavaScript execCommand to copy hidden text to clipboard, we convert it to a text input first.