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')(已弃用)
支持情况:截至 2015 年 4 月左右,大多数浏览器都支持此方法。如 Internet Explorer 10+、Google Chrome 43+、Mozilla Firefox 41+、Opera 29+。
使用方式:访问是同步的,即会停止页面中的 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'); } });