如何将文本复制到剪贴板(多浏览器)?
相关:Trello如何访问用户的剪贴板?
如何将文本复制到剪贴板(多浏览器)?
相关:Trello如何访问用户的剪贴板?
当前回答
我用过clipboard.js。
我们可以在npm上获得:
npm install clipboard --save
还有Bower
bower install clipboard --save
新ClipboardJS(“#btn1”);document.querySelector(“#btn2”).addEventListener(“click”,()=>document.querySelector(“#btn1”).dataset.clipboardText=Math.random());<script src=“https://cdn.jsdelivr.net/npm/clipboard@2.0.8/dist/cclipboard.min.js“></script><button id=“btn1”数据剪贴板text=“要复制的文本位于此处”>复制到剪贴板</按钮><button id=“btn2”>单击此处更改数据剪贴板文本</button><br/><br/><input type=“text”placeholder=“粘贴到此处查看剪贴板”/>
更多用法和示例请访问https://zenorocha.github.io/clipboard.js/.
其他回答
clipboard.js是一个小型的非Flash实用程序,允许将文本或HTML数据复制到剪贴板。它非常容易使用,只需包含.js并使用如下内容:
<button id='markup-copy'>Copy Button</button>
<script>
document.getElementById('markup-copy').addEventListener('click', function() {
clipboard.copy({
'text/plain': 'Markup text. Paste me into a rich text editor.',
'text/html': '<i>here</i> is some <b>rich text</b>'
}).then(
function(){console.log('success'); },
function(err){console.log('failure', err);
});
});
</script>
clipboard.js也在GitHub上。
注意:现在已弃用此选项。迁移到此处。
以下方法适用于Chrome、Firefox、Internet Explorer和Edge以及Safari的最新版本(2016年10月发布的第10版增加了复制支持)。
创建一个文本区域,并将其内容设置为要复制到剪贴板的文本。将文本区域附加到DOM。在文本区域中选择文本。调用document.execCommand(“copy”)从dom中删除文本区域。
注意:您不会看到文本区域,因为它是在Javascript代码的同一同步调用中添加和删除的。
如果您自己执行此操作,请注意以下事项:
出于安全原因,这只能从事件处理程序(如单击)调用(与打开窗口一样)。首次更新剪贴板时,Internet Explorer将显示权限对话框。Internet Explorer和Edge将在文本区域聚焦时滚动。execCommand()在某些情况下可能抛出。除非您使用文本区域,否则换行符和制表符可能会被吞入。(大多数文章似乎都建议使用div)当显示Internet Explorer对话框时,文本区域将可见,您需要隐藏它,或使用Internet Explorer特定的剪贴板数据API。在Internet Explorer中,系统管理员可以禁用剪贴板API。
下面的函数应该尽可能干净地处理以下所有问题。如果您发现任何问题或有任何改进建议,请留言。
// Copies a string to the clipboard. Must be called from within an
// event handler such as click. May return false if it failed, but
// this is not always possible. Browser support for Chrome 43+,
// Firefox 42+, Safari 10+, Edge and Internet Explorer 10+.
// Internet Explorer: The clipboard feature may be disabled by
// an administrator. By default a prompt is shown the first
// time the clipboard is used (per session).
function copyToClipboard(text) {
if (window.clipboardData && window.clipboardData.setData) {
// Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
return window.clipboardData.setData("Text", text);
}
else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in Microsoft Edge.
document.body.appendChild(textarea);
textarea.select();
try {
return document.execCommand("copy"); // Security exception may be thrown by some browsers.
}
catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
finally {
document.body.removeChild(textarea);
}
}
}
https://jsfiddle.net/fx6a6n6x/
2018年,你可以这样做:
async copySomething(text?) {
try {
const toCopy = text || location.href;
await navigator.clipboard.writeText(toCopy);
console.log('Text or Page URL copied');
}
catch (err) {
console.error('Failed to copy: ', err);
}
}
它在我的Angular 6+代码中使用如下:
<button mat-menu-item (click)="copySomething()">
<span>Copy link</span>
</button>
如果我传入一个字符串,它就会复制它。如果没有,它会复制页面的URL。
也可以在剪贴板上做更多的体操。在此处查看更多信息:
取消阻止剪贴板访问
由于Chrome 42+和Firefox 41+现在支持document.execCommand('copy')命令,我结合Tim Down的旧答案和Google Developer的答案,创建了两个跨浏览器复制到剪贴板的功能:
函数selectElementContents(el){//复制textarea、pre、div等。if(document.body.createTextRange){//Internet Explorervar textRange=document.body.createTextRange();text范围.移动到元素文本(el);text范围.选择();textRange.execCommand(“复制”);}否则如果(window.getSelection&&document.createRange){//非Internet Explorervar range=document.createRange();range.selectNodeContents(el);var sel=window.getSelection();sel.removeAllRanges();sel.addRange(范围);尝试{var success=document.execCommand('copy');var msg=成功?'success':'不成功';console.log('复制命令为'+msg);}捕获(错误){console.log(“糟糕,无法复制”);}}}//结束函数selectElementContents(el)函数make_copy_button(el){var copy_btn=document.createElement('input');copy_btn.type=“按钮”;el.parentNode.insertBefore(copy_btn,el.nexSibling);copy_btn.onclick=函数(){selectElementContents(el);};if(document.queryCommandSupported(“copy”)||parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]) >= 42) {//复制适用于Internet Explorer 4+、Chrome 42+、Firefox 41+、Opera 29+copy_btn.value=“复制到剪贴板”;}其他{//仅适用于Safari和旧版Chrome、Firefox和Operacopy_btn.value=“全选(然后按Ctrl+C复制)”;}}/*注意:document.queryCommandSupported(“copy”)在支持复制的浏览器上应返回“true”,但Chrome版本42到47中存在一个错误,使其返回“false”。所以在那些版本的Chrome功能检测不起作用!看见https://code.google.com/p/chromium/issues/detail?id=476508*/make_copy_button(document.getElementById(“标记”));<pre-id=“markup”>可以通过跨浏览器支持复制或选择的文本。</pre>
我喜欢这个:
<input onclick="this.select();" type='text' value='copy me' />
如果用户不知道如何在操作系统中复制文本,那么他们很可能也不知道如何粘贴。因此,只需自动选择它,剩下的留给用户。