var text = "Example text to appear on clipboard"; navigator.clipboard.writeText(text).then(function() { console.log('Async: Copying to clipboard was successful!'); }, function(err) { console.error('Async: Could not copy text: ', err); });
2. document.execCommand(‘copy’)(已弃用)
该方法在大多数浏览器中都有一定支持,但它是同步操作,会阻止页面中的 JavaScript 执行,直到操作完成。文本是从 DOM 中读取并放置到剪贴板的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
copyTextareaBtn.addEventListener('click', function(event) { var copyTextarea = document.querySelector('.js-copytextarea'); copyTextarea.focus(); copyTextarea.select();
try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copying text command was ' + msg); } catch (err) { console.log('Oops, unable to copy'); } });
3. 综合方法(Async + Fallback)
由于新的 Async Clipboard API 浏览器支持程度有限,通常需要结合 document.execCommand('copy') 方法以实现更好的浏览器兼容性。