본문 바로가기
FRONT-END/ERROR & EXCEPTION

[JS]Uncaught TypeError : Cannot read properties of undefined (reading 'writeText')

by 개남 2022. 12. 22.

화면에 txa_test라는 id를 가진 textarea의 내용을 클립보드에 copy를 하려고 navigator.clipboard.writeText()함수를 사용했는데 실행하니까 에러가 발생했습니다.

$(".btn").click(()=> {
  navigator.clipboard.writeText( $("#txa_test").val());
})

Uncaught TypeError : Cannot read properties of undefined (reading 'writeText') 

에러가 발생한 이유는 writeText()가 http에서는 동작하지 않기 때문이었습니다.

Secure context: This feature is available only in secure contexts (HTTPS), 
in some or all supporting browsers.

 

해결방법은 execCommand 함수로 대체해서 사용하시면 됩니다.

수정코드

$(".btn").click(()=> {
    const textArea = document.getElementById("txa_test");
    textArea.select();
    document.execCommand('copy');
})

댓글