如何将文本复制到剪贴板(多浏览器)?
相关:Trello如何访问用户的剪贴板?
如何将文本复制到剪贴板(多浏览器)?
相关:Trello如何访问用户的剪贴板?
当前回答
我非常成功地使用了这个(没有jQuery或任何其他框架)。
function copyToClp(txt){
var m = document;
txt = m.createTextNode(txt);
var w = window;
var b = m.body;
b.appendChild(txt);
if (b.createTextRange) {
var d = b.createTextRange();
d.moveToElementText(txt);
d.select();
m.execCommand('copy');
}
else {
var d = m.createRange();
var g = w.getSelection;
d.selectNodeContents(txt);
g().removeAllRanges();
g().addRange(d);
m.execCommand('copy');
g().removeAllRanges();
}
txt.remove();
}
警告
制表符转换为空格(至少在Chrome中)。
其他回答
通过使用最新的剪贴板API和用户交互,这可以直接实现:
copy.addEventListener(“pointerdown”,()=>navigator.cclipboard.writeText(“Hello World!”))<button id=“copy”>复制Hello World</按钮>
我不愿意就此再加一个答案,但我想帮助像我这样的菜鸟,因为这是谷歌排名第一的结果。
在2022年,要将文本复制到剪贴板,您需要使用一行。
navigator.clipboard.writeText(textToCopy);
这将返回一个Promise,如果它复制,则该Promise将被解析,如果失败,则该Promise将被拒绝。
完整的工作功能如下:
async function copyTextToClipboard(textToCopy) {
try {
await navigator.clipboard.writeText(textToCopy);
console.log('copied to clipboard')
} catch (error) {
console.log('failed to copy to clipboard. error=' + error);
}
}
警告!如果您在测试时打开了Chrome开发工具,它将失败,因为浏览器要启用剪贴板,需要将窗口聚焦。这是为了防止随意网站更改剪贴板(如果你不想的话)。开发工具窃取了这一焦点,所以关闭开发工具,你的测试就会成功。
如果您想将其他内容(图像等)复制到剪贴板,请查看这些文档。
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
这在浏览器中得到了很好的支持,您可以使用它。如果您担心Firefox,请使用权限查询来显示或隐藏按钮(如果浏览器支持)。https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query
该代码于2021 5月测试。在Chrome、IE和Edge上工作下面的message参数是要复制的字符串值。
<script type="text/javascript">
function copyToClipboard(message) {
var textArea = document.createElement("textarea");
textArea.value = message;
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
alert('Copying text command was ' + msg);
} catch (err) {
alert('Unable to copy value , error : ' + err.message);
}
document.body.removeChild(textArea);
}
</script>
我把我认为最好的东西放在一起了。
使用cssText避免Internet Explorer中的异常,而不是直接使用样式。如果有选择,则恢复选择设置为只读,以便移动设备上不会出现键盘有一个适用于iOS的解决方案,因此它实际上可以像通常阻止execCommand一样工作。
这里是:
const copyToClipboard = (function initClipboardText() {
const textarea = document.createElement('textarea');
// Move it off-screen.
textarea.style.cssText = 'position: absolute; left: -99999em';
// Set to readonly to prevent mobile devices opening a keyboard when
// text is .select()'ed.
textarea.setAttribute('readonly', true);
document.body.appendChild(textarea);
return function setClipboardText(text) {
textarea.value = text;
// Check if there is any content selected previously.
const selected = document.getSelection().rangeCount > 0 ?
document.getSelection().getRangeAt(0) : false;
// iOS Safari blocks programmatic execCommand copying normally, without this hack.
// https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
const editable = textarea.contentEditable;
textarea.contentEditable = true;
const range = document.createRange();
range.selectNodeContents(textarea);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
textarea.setSelectionRange(0, 999999);
textarea.contentEditable = editable;
}
else {
textarea.select();
}
try {
const result = document.execCommand('copy');
// Restore previous selection.
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
return result;
}
catch (err) {
console.error(err);
return false;
}
};
})();
用法:复制到剪贴板(“部分文本”)
我非常成功地使用了这个(没有jQuery或任何其他框架)。
function copyToClp(txt){
var m = document;
txt = m.createTextNode(txt);
var w = window;
var b = m.body;
b.appendChild(txt);
if (b.createTextRange) {
var d = b.createTextRange();
d.moveToElementText(txt);
d.select();
m.execCommand('copy');
}
else {
var d = m.createRange();
var g = w.getSelection;
d.selectNodeContents(txt);
g().removeAllRanges();
g().addRange(d);
m.execCommand('copy');
g().removeAllRanges();
}
txt.remove();
}
警告
制表符转换为空格(至少在Chrome中)。