示例
谷歌浏览器:版本 94.0.4606.71(正式版本)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
textarea {
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<textarea id="textarea1"></textarea>
<input type="button" id="write-to" value="Write To System Clipboard">
<br>
<textarea id="textarea2"></textarea>
<input type="button" id="read-from" value="Read From System Clipboard">
<script type="text/javascript">
window.onload = function(event) {
// console.log(event)
main()
}
function main() {
const textarea1 = document.querySelector("#textarea1")
const textarea2 = document.querySelector("#textarea2")
const buttonWrite = document.querySelector("#write-to")
const buttonRead = document.querySelector("#read-from")
buttonWrite.onclick = (event) => {
const content = textarea1.value
// 写文本内容到系统剪贴板
navigator.clipboard.writeText(content).then(function() {
/* clipboard successfully set */
}, function(error) {
/* clipboard write failed */
console.log(error)
})
}
buttonRead.onclick = (event) => {
// 从系统剪贴板读文本内容
navigator.clipboard.readText().then((result) => {
console.log(result)
textarea2.value = result
})
}
}
</script>
</body>
</html>
参考
Web technology for developers > Web APIs > Clipboard > Clipboard.writeText()
Web technology for developers > Web APIs > Clipboard > Clipboard.readText()