Copy to Clipboard

Using the Clipboard API (Modern Browsers)

The Clipboard API is the recommended way to copy text to the clipboard in modern browsers. Here’s how you can do it:

<!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>
<input type="text" id="textToCopy" value="Hello, World!" />
<button id="copyButton">Copy to Clipboard</button>

<script>
document.getElementById('copyButton').addEventListener('click', () => {
const textToCopy = document.getElementById('textToCopy').value;
navigator.clipboard.writeText(textToCopy)
.then(() => {
console.log('Text copied to clipboard');
})
.catch(err => {
console.error('Failed to copy: ', err);
});
});
</script>

</body>
</html>

Using document.execCommand (Older Browsers)

If you need to support older browsers that do not support the Clipboard API, you can use the document.execCommand method. Here’s an example:

<!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>
<input type="text" id="textToCopy" value="Hello, World!" />
<button id="copyButton">Copy to Clipboard</button>

<script>
document.getElementById('copyButton').addEventListener('click', () => {
const textToCopy = document.getElementById('textToCopy');
textToCopy.select();
document.execCommand('copy');
console.log('Text copied to clipboard');
});
</script>
</body>
</html>

Notes:

  • The Clipboard API is asynchronous and returns a promise, which is why you can use .then() and .catch() to handle success and errors.
  • The document.execCommand method is synchronous and may not work in all contexts (e.g., it requires a user gesture).
  • Always ensure that your web application is served over HTTPS when using the Clipboard API for security reasons.