기존에 텍스트 복사를 구현하려면
document.execCommand("copy") 을 이용했다.
그러나 execCommand 메서드는 Deprecated 되었으며,
대안으로 훨씬 쉽고 강력한 Clipboard API 가 나왔다.
window.navigator.clipboard.writeText() 메서드를 사용하면,
아주 쉽게 텍스트를 클립보드에 복사해둘 수 있다.
너무나 쉽고 좋아서 정리해두지 않을 수 없다.
navigator.clipboard.writeText("복사할 텍스트") 호출하면 끝!
비동기로 복사를 수행하고 Promise 를 반환하므로, 복사가 완료되었을 때 수행할 작업을 then의 콜백함수로 넘어주면 된다.
// writeText()의 인자로 넣은 텍스트가 복사된다.
window.navigator.clipboard.writeText("복사될 텍스트").then(() => {
// 복사가 완료되면 이 부분이 호출된다.
alert("복사 완료!");
});
<!DOCTYPE html>
<html lang="ko">
<head>
<title>복사</title>
</head>
<body>
<!-- textarea와 button 생성 -->
<textarea id="myTextarea"></textarea>
<button id="myButton">복사</button>
</body>
<script>
// $textarea
const myTextarea = document.getElementById("myTextarea");
// button 클릭 이벤트
document.getElementById("myButton").onclick = () => {
// textarea의 내용을 복사한다.
window.navigator.clipboard.writeText(myTextarea.value).then(() => {
// 복사가 완료되면 호출된다.
alert("복사완료");
});
};
</script>
</html>
<실행 화면>
<!DOCTYPE html>
<html lang="ko">
<head>
<title>복사</title>
</head>
<body>
<!-- div와 button 생성 -->
<div id="myDiv">div의 내용입니다.</div>
<button id="myButton">복사</button>
</body>
<script>
// div 취득
const myDiv = document.getElementById("myDiv");
// button 클릭 이벤트
document.getElementById("myButton").onclick = () => {
// div의 내용(textContent)을 복사한다.
window.navigator.clipboard.writeText(myDiv.textContent).then(() => {
// 복사가 완료되면 호출된다.
alert("복사완료");
});
};
</script>
</html>
read(), write() 등의 메서드도 제공된다고 한다._
자세한 내용은 레퍼런스를 참고하자._
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
clipboard API 는 localhost나 https 환경에서만 동작한다.
MDN 상에서도 https 에서만 가능한 기능이라고 명시되어 있다.
Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
만약 서버에 배포했는데, https가 아닌 http라면 아래와 같은 에러코드를 만나게 된다.
Uncaught TypeError: Cannot read properties of undefined (reading 'writeText')
정석적인 해결 방법은 https로 서비스하는 것 이지만,
여의치 않다면, execCommand('copy')를 사용할 수 밖에 없지 않나 싶다.
execCommand가 deprecated되어 권장하긴 어렵지만, 아래와 같은 코드로 기능 구현 자체는 가능할 것이다.
// 텍스트 복사 기능 구현
function copyText() {
// clipboard API 사용
if (navigator.clipboard !== undefined) {
navigator.clipboard
.writeText(`복사할 텍스트`)
.then(() => {
alert('텍스트가 복사되었습니다.');
});
} else {
// execCommand 사용
const textArea = document.createElement('textarea');
textArea.value = `복사할 텍스트`;
document.body.appendChild(textArea);
textArea.select();
textArea.setSelectionRange(0, 99999);
try {
document.execCommand('copy');
} catch (err) {
console.error('복사 실패', err);
}
textArea.setSelectionRange(0, 0);
document.body.removeChild(textArea);
alert('텍스트가 복사되었습니다.');
}
};