텍스트 잘라내기 및 붙여넣기는 일반적으로 앱과 특히 데스크톱 애플리케이션에서 흔히 사용되는 기능 중 하나입니다. 웹에서 텍스트를 복사하려면 어떻게 해야 하나요? 이전 방식과 새로운 방식이 있습니다. 사용되는 브라우저에 따라 다릅니다.
최신 방식
Async Clipboard API 사용
Clipboard.writeText() 메서드는 문자열을 가져와서 텍스트가 클립보드에 성공적으로 작성되면 확인되는 Promise를 반환합니다. Clipboard.writeText()는 포커스가 있는 window 객체에서만 사용할 수 있습니다.
기존 방식
document.execCommand() 사용
document.execCommand('copy')를 호출하면 복사가 성공했는지 여부를 나타내는 불리언 값이 반환됩니다. 클릭 핸들러와 같은 사용자 동작 내에서 이 명령어를 호출합니다. 이 방식은 Async Clipboard API와 비교했을 때 제한사항이 있습니다. execCommand() 메서드는 DOM 요소에서만 작동합니다. 동기식이므로 많은 양의 데이터, 특히 어떤 방식으로든 변환하거나 삭제해야 하는 데이터를 복사하면 페이지가 차단될 수 있습니다.
점진적 개선
const copyButton = document.querySelector('#copyButton');
const out = document.querySelector('#out');
if ('clipboard' in navigator) {
copyButton.addEventListener('click', () => {
navigator.clipboard.writeText(out.value)
.then(() => {
console.log('Text copied');
})
.catch((err) => console.error(err.name, err.message));
});
} else {
copyButton.addEventListener('click', () => {
const textArea = document.createElement('textarea');
textArea.value = out.value;
textArea.style.opacity = 0;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const success = document.execCommand('copy');
console.log(`Text copy was ${success ? 'successful' : 'unsuccessful'}.`);
} catch (err) {
console.error(err.name, err.message);
}
document.body.removeChild(textArea);
});
}
추가 자료
- 클립보드 액세스 차단 해제 (최신 방식)
- 잘라내기 및 복사 명령어 (기존 방식)
데모
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 copy text</title>
</head>
<body>
<h1>How to copy text</h1>
<textarea rows="3">
Some sample text for you to copy. Feel free to edit this.</textarea
>
<button type="button">Copy</button>
</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 textarea = document.querySelector('textarea');
const button = document.querySelector('button');
button.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(textarea.value);
} catch (err) {
console.error(err.name, err.message);
}
});