관련지식
javascript

웹사이트들을 보다보면 버튼을 클릭하면 URL이나 특정 텍스트를 클립보드에 복사해주는 기능을 본 적이 있으실 겁니다. 이번엔 그 기능을 구현하는 메카니즘과 방법에 대해 살펴보려고 합니다. 물론 clipboard.js 같은 이미 만들어져있는 기능을 쓰면 되지만 평소에 잘 안 쓸법한 부분도 있어 한번 해보시는것도 좋을것입니다.

동작 방식

자바스크립트에서 바로 클립보드로 복사하는 것은 불가능합니다. 정확히 말하면 자바스크립트로 복사를 할 것이지만 HTML이 반드시 필요합니다.

  1. 복사할 문자열을 input 태그에 저장
  2. input 태그의 문자열을 선택
  3. 클립보드로 복사
  4. 선택 range 해제
  5. 포커스 이동

클립보드에 복사하기 위해선 1~3 까지의 절차만 있으면 되지만 4,5 절차를 추가하여 깔끔하게 마무리 할 수도 있습니다.(브라우저 종류에따라 4번 기능은 동작 안할 수 있습니다.)

주요 코드

주요 코드는 아래 세줄 입니다.

  1. input.select();
  2. document.execCommand("copy");
  3. document.getSelection().removeAllRanges();

select() 함수는 input 와 textarea 태그에서 사용할수 있는 함수로 모든 문자열을 선택하게 해줍니다.

참고 : https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select

execCommand() 함수는 문서의 편집 가능한 영역을 변경할수 있게 해주는 여러가지 기능을 제공합니다. 블로그 등에서 사용되는 많은 에디터들은 이 기능을 활용하는 것입니다.

참고 : https://developer.mozilla.org/ko/docs/Web/API/Document/execCommand#Commands

document.getSelection().removeAllRanges() 함수는 문서 전체에서 선택 범위가 지정된 영역을 해제하는 기능입니다. 텍스트 자체를 삭제하진 않습니다.

참고 : https://developer.mozilla.org/ko/docs/Web/API/Selection

위 함수들을 적절히 사용하면 클립보드로 복사하는 기능을 어렵지 않게 만들 수 있습니다!

최종 샘플

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>CSS Template</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. </head>
  8. <body>
  9. <input id="code_html" type="text" value="삼겹살" autocomplete="off" readonly="">
  10. <input type="button" value="복사"/>
  11. <input id="code_direct" type="text" value="족발" autocomplete="off" readonly="">
  12. <input type="button" value="복사"/>
  13. <input id="code_reddit" type="text" value="수육" autocomplete="off" readonly="">
  14. <input type="button" value="복사"/>
  15. <script>
  16. document.addEventListener("click", function(e) {
  17. var t = e.target;
  18. var input = t.previousElementSibling;
  19. input.select(); //문자열 전체 선택
  20. document.execCommand("copy"); //복사
  21. document.getSelection().removeAllRanges(); //선택 영역 해제
  22. t.focus(); //input.select(); 때 옮겨진 포커스를 원래대로 돌린다
  23. alert("ctrl + v 해서 복사된 값을 확인해보세요.");
  24. });
  25. </script>
  26. </body>
  27. </html>