Create a Copy Text or Link to the Clipboard Button Using JavaScript (Copy To Clipboard)

Updated: July 15th, 2023, 12:21:36 IST
Published: July 14th, 2023
Create a Copy Text or Link to the Clipboard Button Using JavaScript (Copy To Clipboard)
Title: Create a Copy Text or Link to the Clipboard Button Using JavaScript (Copy To Clipboard)

To add a clipboard copy button for copying any text value, you can use JavaScript along with the Clipboard API. With the new Clipboard API, you can copy text to the clipboard using the navigator.clipboard.writeText() method.

When creating web pages or applications, you can allow users to simply click a button or icon to copy the desired text and paste for many purposes.

You can enhance the user experience by providing a more intuitive and user-friendly way to copy text. With a copy button or icon, users can quickly and easily copy text with a single click.

 

Copy Text to the Clipboard

With the new Clipboard API, you can copy text to the clipboard using the navigator.clipboard.writeText() method. Here's an example of a code snippet that we are using to copy text to the clipboard using the Clipboard API:

<div>
    <p id="CopyText">Solvprog.com - Solutions to Every code & problems, the best tutorial and step by step guide for each solutions.</p>
    <button class="btn" onclick="copythistext()">Copy!</button>    
    </div>
<script>
let textToCopy = document.getElementById('CopyText').innerHTML;
const copythistext = async () => {
    try {
        // Copy the text to the clipboard
        await navigator.clipboard.writeText(textToCopy);
        // Text successfully copied
        console.log("Text copied to clipboard: " + textToCopy);
    }
    catch (error) {
        // An error occurred
        console.error("Failed to copy text: ", error);
  }
}
</script>

 

Check the Browser's Permissions

There are a few things to consider before using the Clipboard API to write text to the clipboard:

Security: The Clipboard API is only available for HTTPS-enabled sites. Ascertain that your website is provided securely using HTTPS.

Permissions: To access the clipboard, the browser may require user permission. You can check for permissions using the navigator.permissions query.

To check if you have write access to the clipboard:

JavaScript code

navigator.permissions.query({ name: 'clipboard-write' }).then(result => {
  if (result.state === 'granted' || result.state === 'prompt') {
    // You have permission to write to the clipboard
    // Proceed with the copy operation
    alert("Write access granted!");

  } else {
    // You don't have permission to write to the clipboard
    // Handle the lack of permission accordingly
  }
}).catch(error => {
  // An error occurred while checking the permissions
  // Handle the error gracefully
});

The above code checks the clipboard-write permission and handles the different states (granted, prompt, or denied) accordingly. It allows you to confirm before if you have the necessary permissions, ensuring that the functionality works well.

 

Copy text to the Clipboard Example

An example that you can use and see how to works with the copy text to the clipboard feature:

Create HTML file named index.html, try and use the following complete code.

<!DOCTYPE html>
<html>

<head>
<title>Copy Text To Clipboard!</title>
<style>
body{
margin:0;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
main h1,p,img{
    margin: 0;
	padding:10px;
}

</style>
</head>

<body>
<main>
    <div>
    <p id="CopyText">Solvprog.com - Solutions to Every code & problems, the best tutorial and step by step guide for each solutions.</p>
    <button class="btn" onclick="copythistext()">Copy!</button>    
    </div>
    <h1>Copy Text To Clipboard!</h1>
<p>A paragraph is written here.</p>
<p>This is my second paragraph, and <a href="https://solvprog.com">This is my website link</a></p>

<img src="https://solvprog.com/image/solvprog.jpg" alt="Solvprog.com" width="200" height="40">
</main>

<script>
let textToCopy = document.getElementById('CopyText').innerHTML;
const copythistext = async () => {
    try {
        // Copy the text to the clipboard
        await navigator.clipboard.writeText(textToCopy);
        // Text successfully copied
        console.log("Text copied to clipboard: " + textToCopy);
    }
    catch (error) {
        // An error occurred
        console.error("Failed to copy text: ", error);
  }
}
</script>
</body>
</html>

 

 

To copy text using the new Clipboard API, you can practice how to use it with following these steps:

  1. Use the navigator.clipboard.writeText() method to copy the selected text to the clipboard.

  2. This method accepts a single parameter - the text to be copied.
  3. It returns a promise that resolves if the text is successfully copied and rejects if there is an error. You can handle the promise using the .then() and .catch() methods for success and error output, respectively.
  4. Alternatively, you can use the async/await syntax to handle the promise in a more concise way.
  5. Inside the try block, await the writeText() method and log a success message to the console.
  6. In the catch block, log an error message along with the error object.

 

Method 1:

navigator.clipboard.writeText("This is the text to be copied").then(() => {
  console.log('Content copied to clipboard');
  /* Resolved - text copied to clipboard successfully */
},() => {
  console.error('Failed to copy');
  /* Rejected - text failed to copy to the clipboard */
});

 

Method 2: use async/await alongside try/catch:

async function copyContent() {
  try {
    await navigator.clipboard.writeText('This is the text to be copied');
    console.log('Content copied to clipboard');
    /* Resolved - text copied to clipboard successfully */
  } catch (err) {
    console.error('Failed to copy: ', err);
    /* Rejected - text failed to copy to the clipboard */
  }
}

 

If the text is successfully copied to the clipboard, the promise is resolved. This means that it's successfully completed.

On the other hand, if there was an issue while copying the text, the promise is rejected. This indicates that error is encountered.

By checking the state of the promise, you can determine whether the text was copied successfully or if there was a problem during the copying process.

In this post, you learned how to use the Clipboard API using JavaScript to copy text to the clipboard without having to think outside the box or install any JavaScript libraries.