How to Copy to the Clipboard in JavaScript (Across Browsers)
Overview
To copy text to the clipboard, you can utilize three primary browser APIs:
General Development Considerations
Implementation
Async Fallback
For the best browser coverage, combine the Async Clipboard API with a fallback to document.execCommand('copy'):
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); }); }
Clipboard API Comparison
API | Features | Support | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Text-focused, asynchronous, supports HTTPS | Chrome 66 (March 2018), works in inactive tabs | ||||||||||||
document.execCommand('copy') | Synchronous, reads text from DOM | Most browsers (as of April 2015), displays permission prompts | ||||||||||||
Overriding the Copy Event | Can modify clipboard content from any copy event, supports various data formats | Not directly related to the question |
The above is the detailed content of How Do I Copy Text to the Clipboard in JavaScript Across All Browsers?. For more information, please follow other related articles on the PHP Chinese website!