Cách làm hiện đại
Sử dụng Async Clipboard API
Để đọc văn bản từ khay nhớ tạm của người dùng theo phương thức lập trình, chẳng hạn như sau khi người dùng nhấp vào một nút, bạn có thể sử dụng phương thức readText() của Async Clipboard API. Nếu bạn chưa cấp quyền đọc nội dung trên bảng nhớ tạm, thì lệnh gọi đến navigator.clipboard.readText() sẽ yêu cầu quyền này trong lần gọi đầu tiên đến phương thức.
const pasteButton = document.querySelector('#paste-button');
pasteButton.addEventListener('click', async () => {
try {
const text = await navigator.clipboard.readText()
document.querySelector('textarea').value += text;
console.log('Text pasted.');
} catch (error) {
console.log('Failed to read clipboard');
}
});
Cách cổ điển
Sử dụng document.execCommand()
Bằng cách sử dụng document.execCommand('paste'), bạn có thể dán nội dung trong bảng nhớ tạm tại điểm chèn (phần tử HTML hiện được đặt làm tiêu điểm). Phương thức execCommand trả về một giá trị boolean cho biết liệu sự kiện paste có thành công hay không. Tuy nhiên, phương thức này có những hạn chế, chẳng hạn như vì là phương thức đồng bộ nên việc dán một lượng lớn dữ liệu có thể chặn trang.
pasteButton.addEventListener('click', () => {
document.querySelector('textarea').focus();
const result = document.execCommand('paste')
console.log('document.execCommand result: ', result);
})
Cải tiến tăng dần
pasteButton.addEventListener('click', async () => {
try {
const text = await navigator.clipboard.readText()
document.querySelector('textarea').value += text;
console.log('Text pasted.');
} catch (error) {
console.log('Failed to read clipboard. Using execCommand instead.');
document.querySelector('textarea').focus();
const result = document.execCommand('paste')
console.log('document.execCommand result: ', result);
}
});
Tài liệu đọc thêm
Bản minh hoạ
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="icon"
href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎉</text></svg>"
/>
<title>How to paste text</title>
</head>
<body>
<h1>How to paste text</h1>
<p>
<button type="button">Paste</button>
</p>
<textarea></textarea>
</body>
</html>CSS
:root {
color-scheme: dark light;
}
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 1rem;
font-family: system-ui, sans-serif;
}
button {
display: block;
}
JS
const pasteButton = document.querySelector('button');
pasteButton.addEventListener('click', async () => {
try {
const text = await navigator.clipboard.readText()
document.querySelector('textarea').value += text;
console.log('Text pasted.');
} catch (error) {
console.log('Failed to read clipboard. Using execCommand instead.');
document.querySelector('textarea').focus();
const result = document.execCommand('paste')
console.log('document.execCommand result: ', result);
}
});