최신 방식
Async Clipboard API 사용
예를 들어 버튼 클릭 후 사용자의 클립보드에서 텍스트를 프로그래매틱 방식으로 읽으려면 readText() 메서드를 사용하면 됩니다. 클립보드를 읽을 권한이 아직 부여되지 않은 경우 navigator.clipboard.readText()를 호출하면 메서드를 처음 호출할 때 권한을 요청합니다.
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');
}
});
기존 방식
document.execCommand() 사용
document.execCommand('paste')를 사용하면 삽입 지점 (현재 포커스가 맞춰진 HTML 요소)에 클립보드 콘텐츠를 붙여넣을 수 있습니다. execCommand 메서드는 paste 이벤트가 성공했는지 여부를 나타내는 불리언 값을 반환합니다. 하지만 이 메서드에는 제한사항이 있습니다. 예를 들어 동기식이므로 많은 양의 데이터를 붙여넣으면 페이지가 차단될 수 있습니다.
pasteButton.addEventListener('click', () => {
document.querySelector('textarea').focus();
const result = document.execCommand('paste')
console.log('document.execCommand result: ', result);
})
점진적 개선
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);
}
});
추가 자료
데모
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);
}
});