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
'Frontend > 모던자바스크립트' 카테고리의 다른 글
parseInt()와 Number()의 차이 그리고.. (0) | 2023.01.02 |
---|---|
return false 활용 (0) | 2022.12.28 |
window.onload()는 쓰지말자.(feat. readyState) (0) | 2022.11.08 |
wrapper 이벤트리스너 사용 최소화하기 (2) | 2022.10.07 |
이벤트 중복호출 아무리해도 해결안될때 (0) | 2022.10.06 |