-->

[Javacsript] 클립보드에 복사하기

 

Clipboard에 복사하는 방법은 전통적으로 document.execCommand('copy') 방식을 써왔다.

      const textArea = document.createElement('textarea');
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.select();
      try {
        document.execCommand('copy');
      } catch (err) {
        console.error('Unable to copy to clipboard', err);
      }
      document.body.removeChild(textArea);

해당 방법은 MDN 피셜 Deprecated

 

하지만 Clipboard API가 나와서 손쉽게 가능해졌다.

window.navigator.clipboard.writeText(window.location.href).then(() => console.log('success'));

 

다만 해당 API는 HTTPS에서만 작업이 가능해 http dev 환경에서는 불가능하다.

따라서 요렇게 분기 처리하면 되시겠다.

js

const unsecuredCopyToClipboard = (text) => {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  document.body.appendChild(textArea);
  textArea.select();
  try {
    document.execCommand('copy');
  } catch (err) {
    console.error('Unable to copy to clipboard', err);
  }
  document.body.removeChild(textArea);
  afterCopy();      
};

let target = window.location.href; //현재 URL이나 복사하자

$('#copyClip').click(() => {
  $('#layer').hide();

  if (window.isSecureContext && navigator.clipboard) 
    navigator.clipboard.writeText(target).then(() => afterCopy());
  else 
    unsecuredCopyToClipboard(target);      
});

function afterCopy() {
  $('#layer').toggle(500);

  setTimeout(() => {
    $('#layer').toggle(500);
  }, 1500);
}

jQuery 못 잃어..

 

html

<!-- 알림 메세지   -->
<div id="layer" style="display: none">
  클립보드에 복사되었습니다.
</div>
<button id="copyClip"><img src="아무이미지" alt=""></button>

 

<참조>

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

 

Clipboard - Web APIs | MDN

The Clipboard interface implements the Clipboard API, providing—if the user grants permission—both read and write access to the contents of the system clipboard. The Clipboard API can be used to implement cut, copy, and paste features within a web appl

developer.mozilla.org

https://stackoverflow.com/questions/71873824/copy-text-to-clipboard-cannot-read-properties-of-undefined-reading-writetext

 

Copy text to clipboard: Cannot read properties of undefined reading 'writeText'

I have a button When I clicked on COPY copyImageLinkText({ mouseenter, mouseleave }, e) { this.showCopiedText = !this.showCopiedText navigator.clipboard.writeText(this.imageLink) clearTimeout(

stackoverflow.com

 

+ Recent posts