文章内容
2020/4/16 17:40:04,作 者: 黄兵
Javascript复制功能
最近需要使用到Javascript的复制功能。
查询资料,总结如下内容:
有三种主要的浏览器API可复制到剪贴板:
1、Async Clipboard API [navigator.clipboard.writeText]
- 访问是异步的,并且使用JavaScript Promises,可以编写,因此安全用户提示(如果显示)不会中断页面中的JavaScript。
- 文本可以直接从变量复制到剪贴板。
- 仅在通过HTTPS服务的页面上受支持。
- 在Chrome 66中,活动标签中的页面可以写入剪贴板而没有权限提示。
2、document.execCommand('copy')
- 截至2015年4月,大多数浏览器都支持此功能(请参阅下面的浏览器支持)。
- 访问是同步的,即在页面中停止JavaScript直到完成,包括显示和用户与任何安全提示进行交互。
- 从DOM中读取文本并将其放置在剪贴板上。
- 在2015年4月〜测试期间,只有Internet Explorer被记录为在写入剪贴板时显示权限提示。
3、覆盖复制事件
请参阅剪贴板API文档中有关覆盖复制事件的信息。
允许您通过任何复制事件来修改剪贴板上显示的内容,可以包括除纯文本之外的其他数据格式。
这里没有涵盖,因为它不能直接回答问题。
一般说明:
在控制台中测试代码时,不要期望剪贴板相关的命令能够正常工作。通常,页面需要处于活动状态(异步剪贴板API)或需要用户交互(例如,用户单击)才能允许(document.execCommand('copy')
)访问剪贴板,有关更多详细信息,请参见下文。
下面是一个示例:
function fallbackCopyTextToClipboard(text) { var textArea = document.createElement("textarea"); textArea.value = text; // Avoid scrolling to bottom textArea.style.top = "0"; textArea.style.left = "0"; textArea.style.position = "fixed"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); 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); } 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); }); } var copyBobBtn = document.querySelector('.js-copy-bob-btn'), copyJaneBtn = document.querySelector('.js-copy-jane-btn'); copyBobBtn.addEventListener('click', function(event) { copyTextToClipboard('Bob'); }); copyJaneBtn.addEventListener('click', function(event) { copyTextToClipboard('Jane'); });
<div style="display:inline-block; vertical-align:top;"> <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br /> <button class="js-copy-jane-btn">Set clipboard to JANE</button> </div> <div style="display:inline-block;"> <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard: </textarea> </div>
具体运行效果可以在这里看到:https://deanmarktaylor.github.io/clipboard-test/
评论列表