공유하기, 클립보드 저장
본문 바로가기

Frontend/모던자바스크립트

공유하기, 클립보드 저장

mdn에 따르면 더이상 execCommand('copy')를 사용하지않는다고 하여 코드를 리펙토링 하였다.

 

    function copyToClipboard(val) {
        if(navigator.share) {
            return navigator.share({
                title: 'myblog',
                text: 'shared url',
                url:  window.location.href || val
            }).catch(console.debug);
        }
        const t = document.createElement("textarea");
        t.setAttribute('readonly', true); // for mobile copy
        document.body.appendChild(t);
        t.value = window.location.href || val;
        t.select();
        document.execCommand('copy');
        document.body.removeChild(t);

        alert("copied!");
    }

 

우선 공유하기와 클립저장 두개 기능을 분리해야한다.

그리고 execCommand('copy') 대신에 navigator.clipboard.writeText(...)를 사용하기로 한다.

 

	const share = (val) => {
    	...
    }
	const copyToClipboard = (val) => {
        const t = document.createElement("textarea");
        t.setAttribute('readonly', true); // for mobile copy
        document.body.appendChild(t);
        t.value = window.location.href || val;
        t.select();
        navigator.clipboard.writeText(t.value).then(()=>{
            alert('copied!')
        })
        document.body.removeChild(t);
    }

 

크롬브라우저 콘솔에서는 select()를 쓰지않으면 DomException(Document is not focused)가 나는줄 알았으나

실제코드에서는 정상작동 그것때문은 아닌것같다.

 

https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

 

Document.execCommand() - Web APIs | MDN

When an HTML document has been switched to designMode, its document object exposes an execCommand method to run commands that manipulate the current editable region, such as form inputs or contentEditable elements.

developer.mozilla.org

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_copy_clipboard 

 

W3Schools online HTML editor

The W3Schools online code editor allows you to edit code and view the result in your browser

www.w3schools.com

 

반응형