[javascript] element 내 text를 클립보드로 복사하기

develop, javascript
written byzuhern1zuhern

in

2019. 03. 12


목표: object data를 예쁘게 보이게 하고 내용을 복사하기


object 로 데이터를 말아놨는데,
파일 다운로드 보다는 버튼 클릭으로 복사하는 방식이 간단하지 않을까 생각했디.


textarea에 바로 넣으면 [object Object] 로 표시되더라
JSON.stringify(data)로 변경해서 넣으면 줄바꿈이 안됌


<pre></pre> 안에 object를 bind (vue 사용) 하면 줄바꿈이 예쁘게 됌

이제, 복사를 하려고 검색한 내용.

var copyText = document.getElementById("id-textarea");
copyText.select();                           // Select the text field                
document.execCommand("copy");                // Copy the text inside the text field
alert("Copied the text: " + copyText.value); // Alert the copied text

하지만 나는 pre 안에 있는 텍스트를 복사해야 하기 때문에,
아래와 같이 textarea에 text를 넣고, 그 text를 복사하는 방법으로 복사 완료.


const copyText = document.getElementById("pre-text").textContent; // pre 내 줄바꿈 포함됌
const textArea = document.createElement('textarea');              // 임시 textarea 생성

textArea.textContent = copyText;  // textarea에 pre text를 넣음
document.body.append(textArea);   // body에 textarea 그리기, 그리지 않으면 복사 안됌
textArea.select(); 
document.execCommand("copy");
textArea.remove();                // 임시 textarea 제거

alert('복사되었습니다.');

See the Pen copy text in pre by zuhern (@zuhern) on CodePen.