To copy text to the clipboard with JavaScript, you can use the Clipboard API’s “writeText()“ method. This asynchronous method returns a “promise” that resolves once the text has been copied to the clipboard.
Example
async function copyTextToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Text copied to clipboard:', text);
} catch (err) {
console.error('Failed to copy text:', err);
}
}
const textToCopy = 'Homer, Simpson!';
copyTextToClipboard(textToCopy);
In this code, we defined an “async” function named copyTextToClipboard() that takes a text parameter.
Inside the function, we used the “await” keyword with the “navigator.clipboard.writeText(text)” method to copy the text to the clipboard. If the operation is successful, we log a message to the console, and if it fails, we log an error.
One thing to note is that the “Clipboard API requires user activation”, which means the copyTextToClipboard() function should be called in response to a user action, such as a button click event. Calling this function without user activation may not work due to security restrictions.
Here’s an example of how to use the copyTextToClipboard() function in response to a button click event:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Copy to Clipboard Example</title>
</head>
<body>
<button id="copyButton">Copy Text</button>
<script>
async function copyTextToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Text copied to clipboard:', text);
} catch (err) {
console.error('Failed to copy text:', err);
}
}
const textToCopy = 'Homer, Simpson!';
const copyButton = document.getElementById('copyButton');
copyButton.addEventListener('click', () => {
copyTextToClipboard(textToCopy);
});
</script>
</body>
</html>
In this code, we created a button with the ID copyButton.
When the user clicks the button, the copyTextToClipboard() function is called with the textToCopy variable.

Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.