There are many instances on a website or app where you would want the user/visitor to copy a hidden string or copy content from the website and paste the copied link into a text area or anywhere else. It is the clipboard that is responsible for holding that piece of information temporarily till you hit the paste button.

There are a few methods that can be used to copy a JavaScript string to a clipboard. The string/text copied to the clipboard can be pasted anywhere or automated with a function. But some of these methods may have browser issues.

It is however important to know how to save/copy a string to a clipboard when building websites and web-based applications.

To simply save a string, you have to ensure navigator, navigator.clipboard and navigator.clipboard.writeText. The Clipboard.writeText() allows you to copy the string value directly to the clipboard. We will see how this works shortly.

Let’s take for example;

You create a string and store it as a variable…

let stringText = 'I am a text copied to clipboard';

After creating a string and storing it as a variable, you have to create a function that lets you copy a string to the clipboard.

let stringText = 'I am a text copied to clipboard';
function copyBtn() {
  navigator.clipboard.writeText(stringText);
}

If the function copyBtn() has been assigned to an onClick event in an HTML element, when clicked on, the value of the string will immediately be copied to the clipboard.

Create an HTML <button> which would have a click event that would enable you to copy a string to the clipboard which you can then paste anywhere.

Remember to pass the copyBtn() function to the click event like onclick="copyBtn"

Then create a text area where you can paste the string to.

Create a function to enable you to copy the string to the clipboard

let stringText = 'I am a string, copy me to clipboard';
function copyBtn() {
   navigator.clipboard.writeText(stringText);
};

After writing this function in your javascript file or between a javascript element, then paste the string to the text area.

Conclusion:

You can use the clipboard to store different data such as texts, images, or a hidden string that the user can only access onclick() event. However, make sure you run proper tests to ensure it works on different browsers and devices.