(JS) 클립보드 복사하기

export const copyClipboard = async (url = window.document.location.href) => {
  try {
    await navigator.clipboard.writeText(url);
    alert('링크가 복사되었습니다.');
  } catch (e) {
    console.error(e);
    alert('클립보드 복사에 실패했습니다.');
  }
};

https://web.dev/i18n/ko/async-clipboard/


레거시 방법

export const copyURL = () => {
  let currentUrl = window.document.location.href;
  let t = document.createElement('textarea');
  document.body.appendChild(t);
  t.value = currentUrl;
  t.select();
  document.execCommand('copy');
  document.body.removeChild(t);
 
  alert('링크가 복사되었습니다.');
};

https://sezzled.tistory.com/138