Skip to content

原生javascript复制字符串到剪切板

Published:

navigator.clipboard.writeText()方法可以写入特定字符串到操作系统的剪切板.
该方法返回一个promise.
如果调用者没有写入剪贴板的权限,则会写入失败.

var text = "Hello World";
var promise = navigator.clipboard.writeText(text);
promise.then(function() {
    console.log("clipboard successfully set");
}, function() {
    console.log("clipboard write failed");
});

document.execCommand

document.execCommand("copy")方法可以拷贝当前选中内容到剪贴板.

var text = "Hello World";
var input = document.createElement("input");
// 设置input只读可防止拉起键盘
input.setAttribute("readonly", "readonly");
input.setAttribute("value", text);
document.body.appendChild(input);
// 选择input内的全部文字,防止input.select()在某些情况下没有选中全部内容
input.setSelectionRange(0, text.length);
input.select();
document.execCommand("copy");
document.body.removeChild(input);