概述
有三个主要的浏览器 API 用于复制到剪贴板:
异步剪贴板 API [navigator.clipboard.writeText]
- Chrome 66中提供以文本为中心的部分(2018 年 3 月)
- 访问是异步的并使用JavaScript Promises,可以编写为安全用户提示(如果显示)不会中断页面中的 JavaScript。
- 文本可以直接从变量复制到剪贴板。
- 仅在通过 HTTPS 提供的页面上受支持。
- 在 Chrome 66 页面中,非活动标签可以在没有权限提示的情况下写入剪贴板。
document.execCommand('copy')
(已弃用)
- 自 2015 年 4 月起,大多数浏览器都支持此功能(请参阅下面的浏览器支持)。
- 访问是同步的,即停止页面中的 JavaScript 直到完成,包括显示和用户与任何安全提示进行交互。
- 文本从 DOM 中读取并放置在剪贴板上。
- 在测试期间 ~ 2015 年 4 月,只有 Internet Explorer 被记录为在写入剪贴板时显示权限提示。
覆盖复制事件
- 请参阅有关覆盖复制事件的剪贴板 API 文档。
- 允许您从任何复制事件修改剪贴板上显示的内容,可以包括纯文本以外的其他格式的数据。
- 这里没有涉及,因为它没有直接回答这个问题。
一般开发说明
当您在控制台中测试代码时,不要期望剪贴板相关命令能够正常工作。通常,页面需要处于活动状态(异步剪贴板 API)或需要用户交互(例如用户单击)以允许 ( document.execCommand('copy')
) 访问剪贴板,详情请参见下文。
重要(此处注明 2020/02/20)
请注意,由于这篇文章最初是写在跨域IFRAME和其他IFRAME “沙盒”中的权限的弃用,因此会阻止嵌入式演示“运行代码片段”按钮和“codepen.io 示例”在某些浏览器中工作(包括 Chrome 和 Microsoft Edge )。
要开发创建您自己的网页,请通过 HTTPS 连接提供该页面以进行测试和开发。
这是一个演示代码工作的测试/演示页面:
https ://deanmarktaylor.github.io/clipboard-test/
异步+后备
由于浏览器对新 Async Clipboard 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>
(codepen.io 示例可能不起作用,请阅读上面的“重要”注释)请注意,此代码段在 Stack Overflow 的嵌入式预览中效果不佳,您可以在此处尝试:https ://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors =1011
异步剪贴板 API
请注意,通过 Chrome 66 中的权限 API,可以“请求权限”并测试对剪贴板的访问权限。
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);
});
document.execCommand('复制')
本文的其余部分将介绍document.execCommand('copy')
API 的细微差别和细节。
浏览器支持
JavaScriptdocument.execCommand('copy')
支持已增加,请参阅以下链接了解浏览器更新: (已弃用)
简单示例
(可能无法嵌入本网站,请阅读上面的“重要”说明)
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');
}
});
<p>
<button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button>
<textarea class="js-copytextarea">Hello I'm some text</textarea>
</p>
复杂示例:复制到剪贴板而不显示输入
textarea
如果屏幕上有一个或input
元素可见,上面的简单示例效果很好。
在某些情况下,您可能希望将文本复制到剪贴板而不显示input
/textarea
元素。这是解决此问题的方法的一个示例(基本上是插入元素,复制到剪贴板,删除元素):
使用 Google Chrome 44、Firefox 42.0a1 和 Internet Explorer 11.0.8600.17814 进行测试。
(可能无法嵌入本网站,请阅读上面的“重要”说明)
function copyTextToClipboard(text) {
var textArea = document.createElement("textarea");
//
// *** This styling is an extra step which is likely not required. ***
//
// Why is it here? To ensure:
// 1. the element is able to have focus and selection.
// 2. if the element was to flash render it has minimal visual impact.
// 3. less flakyness with selection and copying which **might** occur if
// the textarea element is not visible.
//
// The likelihood is the element won't even render, not even a
// flash, so some of these are just precautions. However in
// Internet Explorer the element is visible whilst the popup
// box asking the user for permission for the web page to
// copy to the clipboard.
//
// Place in the top-left corner of screen regardless of scroll position.
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
// Ensure it has a small width and height. Setting to 1px / 1em
// doesn't work as this gives a negative w/h on some browsers.
textArea.style.width = '2em';
textArea.style.height = '2em';
// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;
// Clean up any borders.
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
// Avoid flash of the white box if rendered for any reason.
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.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');
}
document.body.removeChild(textArea);
}
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>
补充笔记
仅当用户采取行动时才有效
所有document.execCommand('copy')
调用都必须是用户操作的直接结果,例如单击事件处理程序。这是一种防止在用户不期望的情况下弄乱用户剪贴板的措施。
有关详细信息,请参阅此处的 Google Developers 帖子。
剪贴板 API
注意完整的剪贴板 API 草案规范可以在这里找到:
https ://w3c.github.io/clipboard-apis/
是否支持?
document.queryCommandSupported('copy')
true
如果命令“浏览器支持”,则应返回。
- 如果现在调用将成功,则
document.queryCommandEnabled('copy')
返回。检查以确保从用户启动的线程调用命令并满足其他要求。true
document.execCommand('copy')
但是,作为浏览器兼容性问题的一个示例,Google Chrome 从 2015 年 4 月到 2015 年 10 月仅在true
从document.queryCommandSupported('copy')
用户启动的线程调用命令时才返回。
请注意下面的兼容性详细信息。
浏览器兼容性详情
虽然由于用户单击而对document.execCommand('copy')
包装在try
/catch
块中的简单调用将为您提供最大的兼容性,但使用以下有一些附带条件:
对或document.execCommand
的任何调用都应包含在/块中。document.queryCommandSupported
document.queryCommandEnabled
try
catch
不同的浏览器实现和浏览器版本在调用而不是返回时会抛出不同类型的异常false
。
不同的浏览器实现仍在不断变化,剪贴板 API仍在草稿中,因此请记住进行测试。