반응형

버튼을 클릭했을 때 현재 url 주소를 복사하는 방법입니다.

 

.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <button onclick="copyCurrentURL()">클릭</button>

        <script>
            function copyCurrentURL() {
                // URL 가져오기
                const currentURL = window.location.href;

                // 요소 생성하기 | 꾸미기 | currentURL주소 추가하기
                const input = document.createElement("input");
                input.style.position = "fixed";
                input.style.opacity = "0";
                input.value = currentURL;

                // 문서에 입력요소 추가하기
                document.body.appendChild(input);

                // URL 텍스트 선택하기 || setSelectionRange: 모바일인 경우
                input.select();
                input.setSelectionRange(0, 99999);

                // URL 클립보드에 복사하기
                document.execCommand("copy");

                // 임시 입력 요소 제거하기
                document.body.removeChild(input);

                alert("복사완료" + currentURL);
            }
        </script>
    </body>
</html>

 

위 내용을 사용하다가 아래와같은 경고내용이 등장한 때가 있었습니다.

Signature '(commandId: string, showUI?: boolean | undefined, value?: string | undefined): boolean' is deprecated.

document.execCommand("copy")방법이 실제로 더 이상 사용되지 않다는 내용인 것 같습니다. ( 그냥 HTML에서는 그대로 사용이 가능한 것 같습니다. )

그래서 아래와 같은 방법으로 변경해서 사용을 했습니다.

 

.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <button onclick="copyCurrentURL()">클릭</button>

        <script>
            function copyCurrentURL() {
                const currentURL = window.location.href;

                navigator.clipboard.writeText(currentURL)
                .then(() => {
                    alert('Current URL copied to clipboard: ' + currentURL);
                })
                .catch(err => console.error('Copy Failed:', err));
            }
        </script>
    </body>
</html>

navigator.clipboard.writeText 메서드를 사용해서 현재 URL을 클립보드에 추가합니다.

writeText메서드는 약속을 반환하기 때문에 .then()과 .catch()를 사용하여 성공 및 실패를 처리합니다.

위와같이 사용하면 최신 웹 애플리케이션에서 정상적으로 사용할 수 있습니다. ( 저는 next.js를 사용할 때 빗금이 그려져서 위 방법으로 바꾸었습니다. )

반응형

+ Recent posts