You might consider integrating a copy function when developing intricate web pages and applications. Rather than having users manually highlight the text and use keyboard shortcuts to duplicate it, you can provide a more user-friendly option that allows them to copy text simply by clicking on a button or icon.
This functionality is commonly utilized when an individual needs to duplicate an activation code, a recovery key, a piece of code, or similar items. Additionally, to inform the user that the text has successfully been copied to their clipboard, you can incorporate elements such as an alert or a message displayed on the screen (which may take the form of a modal).
Previously, the command document.execCommand was utilized to achieve this functionality; however, it has now been deprecated. The Clipboard API has emerged as a modern solution, enabling asynchronous reading and writing operations to the system clipboard, as well as the ability to handle clipboard events such as cut, copy, and paste. By leveraging JavaScript's Clipboard API, you can effectively copy text to the clipboard. This API serves as a mechanism for interacting with the clipboard, facilitating both reading from and writing to it.
In this tutorial, you will learn how to utilize the Clipboard API to copy both text and images to the clipboard.
<p id="myText">Hello World</p>
<button class="btn" onclick="copyContent()">Copy!</button>
<script>
let text = document.getElementById('myText').innerHTML;
const copyContent = async () => {
try {
await navigator.clipboard.writeText(text);
console.log('Content copied to clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
}
</script>
How to Examine the Permissions of the Browser
It is essential to recognize that only pages served via HTTPS can utilize the Clipboard API. Prior to making an attempt to write to the clipboard, verify your browser's permissions to ensure that you possess the necessary write access. You can accomplish this by using the navigator's .permissions interface.
navigator.permissions.query({ name: "write-on-clipboard" }).then((result) => {
if (result.state == "granted" || result.state == "prompt") {
alert("Write access granted!");
}
});
Here's how you can copy text to the clipboard using the Clipboard API:
Design a button or any other element that will initiate the copy function.
For example:
<button id="copy-button">Copy Text</button>
Attach an event listener to the button that will initiate the copy process. Within the event listener's function, you will need to invoke the writeText method from the Clipboard API to transfer the text to the clipboard.
For example:
const copyButton = document.querySelector('#copy-button');
const textToCopy = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ...'; // Add your text here
copyButton.addEventListener('click', () => {
navigator.clipboard.writeText(textToCopy)
.then(() => {
console.log('Text copied to clipboard');
})
.catch((err) => {
console.error('Failed to copy text: ', err);
});
});
In the preceding example, we begin by identifying the button with document.querySelector, and subsequently, we attach an event listener to it through the addEventListener method. Within the event listener, we invoke the writeText function from the Clipboard API, providing the text intended for copying as a parameter. Since the writeText function returns a promise, we utilize .then to manage the successful execution and .catch to address any potential errors that may arise.
It is essential to obtain the "clipboard-write" permission for your website. In the absence of this permission, the function navigator.clipboard.writeText will not execute successfully. To implement this, include the subsequent line of code within the head section of your HTML file:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="clipboard-write" content="">
That's all! Upon the user clicking the button, the text will be duplicated to the clipboard. It is important to mention that this approach is compatible with the majority of contemporary web browsers; however, certain older browsers might lack support for it. In such scenarios, you might have to implement a backup solution, like utilizing a hidden input field to hold the text and subsequently selecting it using document.execCommand('copy').
For this particular instance, the previously mentioned strategy will be implemented.
<h1 style="color:crimson;">
Example
</h1>
<input type="text"
value="Example"
id="JtpInput">
<button onclick="copyText()">
Copy text
</button>
<script>
function pyVisualizer() {
var copyJtpText = document.getElementById("JtpInput");
copyJtpText.select();
document.execCommand("copy");
document.getElementById("jtp")
.innerHTML ="Copied the text: "
+ copyJtpText.value;
}
</script>
<p>
To copy the text from the text field, click the button. <br>
Try to paste the text (e.g. ctrl+v)
afterwards in a different window, to see the
effect.
</p>
<p id="jtp"></p>
Output
To copy the text from the designated text field, simply click the button provided. Afterwards, attempt to paste the copied text (for instance, using ctrl+v) into another window to observe the result.