In JavaScript, there are multiple ways to copy text to the clipboard, depending on the browser support.
1. Async Clipboard API [navigator.clipboard.writeText]
Available in Chrome 66, the Async Clipboard API offers asynchronous access to the clipboard. It uses JavaScript Promises, allowing seamless execution without user prompts interrupting the page. Additionally, text can be directly copied to the clipboard from a variable. Note that it only works on pages served over HTTPS.
2. document.execCommand('copy') (Deprecated)
This method is synchronous and supported by most browsers since April 2015. It stops JavaScript execution until the process is complete, potentially displaying security prompts to the user. Text is copied from the DOM to the clipboard.
General Development Notes:
Fallback Method:
To ensure cross-browser compatibility, it's recommended to use a fallback method alongside the Async Clipboard API. Here's an example:
function fallbackCopyTextToClipboard(text) { // Create a textarea element and copy text to it const textArea = document.createElement("textarea"); textArea.value = text; // Append the textarea to the body and set properties document.body.appendChild(textArea); textArea.focus(); textArea.select(); // Execute the copy command try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Fallback: Copying text command was ' + msg); } catch (err) { console.error('Fallback: Oops, unable to copy', err); } // Remove the textarea from the body document.body.removeChild(textArea); } function copyTextToClipboard(text) { if (!navigator.clipboard) { fallbackCopyTextToClipboard(text); return; } navigator.clipboard.writeText(text).then(function() { console.log('Async: Copying to clipboard was successful!'); }, function(err) { console.error('Async: Could not copy text: ', err); }); }
The above is the detailed content of How Can I Efficiently Copy Text to the Clipboard Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!