개발/JavaScript

자바스크립트 - 텍스트를 클립보드에 복사하기 (Copy to Clipboard in Javascript)

피로물든딸기 2023. 6. 19. 19:37
반응형

자바스크립트 전체 링크

 

자바스크립트 파일 다운로드 코드와 유사하다.

 

textarea를 만든 후, textarea의 value에 text를 입력한다.

그리고 textarea를 선택(select)한 후, 복사한다.

이후 불필요한 textarea를 다시 제거한다.

const copyToClipBoard = (text) => {
  let textarea = document.createElement("textarea");
 
  document.body.appendChild(textarea);
  
  textarea.value = text;
  textarea.select();

  document.execCommand("copy");
  document.body.removeChild(textarea);
}

 

하지만 execCommand는 더 이상 권고되지 않는다.

 

대체 방안으로 navigator를 이용하면 된다.

const copyToClipBoard = (text) => {
  navigator.clipboard
    .writeText(text)
    .then(() => console.log(`copy ${text}`))
    .catch((e) => console.log(e));
};

 

readText를 이용하면 클립보드에 저장된 내용을 읽을 수도 있다.

const readClipBoard = () => {
  navigator.clipboard
    .readText()
    .then((text) => console.log(`copy ${text}`))
    .catch((e) => console.log(e));
};
반응형