Skip to content

Instantly share code, notes, and snippets.

@adhrinae
Created June 29, 2018 14:38
Show Gist options
  • Save adhrinae/f704af632ee9294c3fc53d05ac72321b to your computer and use it in GitHub Desktop.
Save adhrinae/f704af632ee9294c3fc53d05ac72321b to your computer and use it in GitHub Desktop.
Copy text to clipboard in browser
/**
* 텍스트를 클립보드로 복사하는 역할을 수행해주는 인스턴스 생성
* window 객체를 직접 주입하여 테스트 가능성 및 역할 명료화(불필요하면 나중에 삭제)
* reference: https://gist.github.com/rproenca/64781c6a1329b48a455b645d361a9aa3
*
* 사용법: new Clipboard(window, document, navigator).copy('text');
*/
export default class Clipboard {
private textArea: HTMLTextAreaElement;
private document: Document;
private userAgent: string;
constructor(private window: Window) {
this.document = window.document;
this.userAgent = window.navigator.userAgent;
}
public copyText(text: string) {
this.createTextArea(text);
this.selectText();
this.copyToClipboard();
}
private createTextArea(text: string) {
this.textArea = this.document.createElement('textarea');
this.textArea.innerText = text;
this.document.body.appendChild(this.textArea);
}
private selectText() {
if (this.isiOS) {
const range = this.document.createRange();
range.selectNodeContents(this.textArea);
const selection = this.window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
this.textArea.setSelectionRange(0, 99999);
} else {
this.textArea.select();
}
}
private copyToClipboard() {
this.document.execCommand('copy');
this.document.body.removeChild(this.textArea);
}
private get isiOS() {
return /ipad|iphone/i.test(this.userAgent);
}
}
@adhrinae
Copy link
Author

실제 사용 시 createTextArea 에서 appendChild 를 하는 타겟 노드를 주입받도록 만드는게 더 유용하다.
iOS 기기의 경우 삽입된 textarea로 강제로 이동하게 되어있기 때문에, 화면 맨 아래로 스크롤 될 수 있기 때문이다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment