개발 🐾/Error

JavaScript 배포후 copy 안되는 문제

JOTOKKI 2024. 8. 22. 11:03
728x90

링크공유와 같은 기능을 구현하기 위해 버튼 클릭시 링크를 복사하는 기능을 은근히 많이 사용하게 되는데요.
이를 구현할때 예전에는 execCommand 함수를 많이 쓰다가 deprecated 되고나서 (리액트 환경) navigator.clipboard.writeText 함수를 많이 쓰게됩니다. 
그런데 분명 local 에서 잘 동작되다가 개발 서버에 배포만 하면 복사가 되지 않습니다. 

보통 개발서버는 https 가 아닌 http로 동작하기 때문에, 보안 정책에 걸리기 때문인 것 같더라구요. 

참조: https://stackoverflow.com/questions/51805395/navigator-clipboard-is-undefined

그래서 이를 해결하기 위해 https 환경일때만 안정적인 navigator.clipboard.writeText 를 사용하고 그렇지 않을때는 deprecated 되었던 execCommand 함수를 사용했더니 잘 동작이 되었습니다.

 

const copyText = "your url";
if(navigator.clipboard && window.isSecureContext) {
    navigator.clipboard
        .writeText(copyText)
        .then(() => {alert("copied!")})
        .catch((err) => { console.log("err -> ", err) });
} else {
    try {
        console.log('copy exec command use');

        const textarea = document.createElement("textarea");
        textarea.value = copyText;
        textarea.style.top = 0;
        textarea.style.left = 0;
        textarea.style.position = "fixed";
        document.body.appendChild(textarea);
        textarea.focus();
        textarea.select();
        const copyExec = document.execCommand('copy');
        document.body.removeChild(textarea);
        if(copyExec) alert("copied!");
        else { console.log("error") }
    } catch (err) {
        console.log("error", err)
    }
}

 

이젠 개발환경에서도 테스트를 할수 있게되었군요! 😊

반응형