浏覽器原生剪貼闆 navigator.clipboard
1. 寫入 navigator.clipboard.writeText
navigator.clipboard.writeText('需要複制的文本').then(() => {
console.log('文本已複制到剪貼闆');
}).catch(err => {
// 如果使用者拒絕剪貼闆權限,則可能發生這種情況
console.error('無法複制文本: ', err);
});
2. 讀取 navigator.clipboard.readText
navigator.clipboard.readText().then(text => {
console.log('粘貼的内容: ', text);
}).catch(err => {
console.error('無法讀取剪貼闆内容: ', err);
});
document.addEventListener('paste', event => {
event.preventDefault();
navigator.clipboard.getText().then(text => {
console.log('Pasted text: ', text);
});
});
浏覽器相容性
相容iOS
// 複制
onCopy(val) {
if (navigator.clipboard) {
return navigator.clipboard.writeText(val).then(text => {
Toast.success("複制成功");
}).catch(err => {
this.onExecCommand(val);
});;
} else {
this.onExecCommand(val);
}
},
onExecCommand(val) {
let input = document.createElement('input');
input.setAttribute('readonly', 'readonly');
input.setAttribute('value', val);
input.style.position = "absolute";
input.style.opacity = 0;
input.style.left = "-999999px";
input.style.top = "-999999px";
document.body.appendChild(input);
input.focus();
input.select();
input.setSelectionRange(0, 9999);
if (document.execCommand('copy')) {
document.execCommand('copy');
Toast.success("複制成功");
}
document.body.removeChild(input);
}