In JavaScript, to copy content to the clipboard, you can use the navigator.clipboard.writeText() method. This is a simple modern browser API for writing content to the clipboard.
Here is an example of using this API:
javascript// The content to copy const textToCopy = "Content to copy"; // Using the Clipboard API to copy content to the clipboard navigator.clipboard.writeText(textToCopy).then(() => { console.log("The content has been successfully copied to the clipboard!"); }).catch(err => { console.error("Failed to copy content: ", err); });
Note that due to security reasons, modern browsers typically require the writeText method to be called within a function triggered by user behavior (such as a click event). If you attempt to call it in non-user-triggered events (e.g., during page load), the browser may block the operation.
Additionally, some browsers may require the page to be served over HTTPS instead of HTTP to allow the use of the Clipboard API.
Here is an example of combining an HTML button with JavaScript code that uses the navigator.clipboard.writeText() method:
html<button id="copyButton">Copy Text</button>
javascriptdocument.getElementById('copyButton').addEventListener('click', function() { const textToCopy = "Content to copy"; navigator.clipboard.writeText(textToCopy).then(() => { console.log("The content has been successfully copied to the clipboard!"); }).catch(err => { console.error("Failed to copy content: ", err); }); });
In this example, when the user clicks the button, the content in textToCopy is copied to the clipboard.