How to copy text to the Clipboard | JavaScript

Copying text to the clipboard in JavaScript involves interacting with the Clipboard API. Here are the details along with examples:

Using the Clipboard API (Async Clipboard API)

The modern and recommended way is to use the Clipboard API, which is asynchronous and provides better control over clipboard interactions.

async function copyToClipboard(text) { try { await navigator.clipboard.writeText(text); console.log("Text copied to clipboard"); } catch (error) { console.error("Failed to copy text: ", error); } } copyToClipboard("Hello, world!");

Fallback Approach (for browsers without Clipboard API)

If the Clipboard API isn't supported, you can provide a fallback method using the document.execCommand() approach mentioned earlier.

async function copyToClipboardFallback(text) { if (navigator.clipboard) { try { await navigator.clipboard.writeText(text); console.log("Text copied to clipboard"); } catch (error) { console.error("Failed to copy text: ", error); } } else { var tempInput = document.createElement("input"); document.body.appendChild(tempInput); tempInput.value = text; tempInput.select(); document.execCommand("copy"); document.body.removeChild(tempInput); console.log("Text copied to clipboard (fallback)"); } } copyToClipboardFallback("Hello, world!");

Using the Document.execCommand() Method (Deprecated)

The execCommand() method, although deprecated, is still widely used to copy text to the clipboard. It works in most browsers but may not be supported in the future.

function copyToClipboard(text) { var tempInput = document.createElement("input"); document.body.appendChild(tempInput); tempInput.value = text; tempInput.select(); document.execCommand("copy"); document.body.removeChild(tempInput); } copyToClipboard("Hello, world!");

How can I copy text to clipboard with JavaScript

Clipboard API

The Clipboard interface represents the Clipboard API, allowing web applications to request both read and write access to the system clipboard, subject to user permissions. The navigator.clipboard API is a more recent addition to the web specification, enabling easier clipboard manipulation, but its support might not be consistent across all browsers. Developers should consider providing fallback solutions for browsers that do not fully implement the navigator.clipboard API.

Conclusion

The Clipboard API offers better security and user control, and it's the recommended way to copy text to the clipboard in modern browsers. However, in some cases, you might need to provide a fallback mechanism for older browsers that don't support the API.