coding/javascript
[크롬 익스텐션] Clipboard 개발 일지
코딩희송
2022. 2. 14. 18:41
설계하기
textarea
생성- 만든
textarea
안보이게 스타일링 - body에 추가
- getSelection()과 createRange()를 사용해 clipboard할 텍스트 선택
- Document.execCommand() 명령어로 copy하기.
- getSelection 영역 초기화
놓쳤던 부분
textArea
엘리먼트에 자체 focus()
, select()
를 사용하였더니 크롬 확장자 개발 특성상 크롬 확장자와 기존 페이지의 input이 충돌하여 먹지 않아서 document.getSelection()
, getSelection.createRange()
를 이용해야 했음.
- 이전 소스:
const textArea = document.createElement('textarea');
textArea.value = text;
(...)
textArea.focus();
textArea.select();
try {
(...)
} catch (err) {
console.log('Error copying to clipboard');
}
(...)
- 수정한 소스:
const textArea = document.createElement('textarea');
textArea.textContent = text;
textArea.style.display = 'hidden';
document.body.appendChild(textArea);
var selection = document.getSelection();
var range = document.createRange();
range.selectNode(textArea);
selection.removeAllRanges();
selection.addRange(range);
try {
(...)
} catch (err) {
console.log('Error copying to clipboard');
}
(...)
발견하기
글쓰기 에디터 만들 때 필수 이해 요소인 createRange와 getSelection 이해하기가 필요.
Selection
사용자의 드래그 제스쳐로 선택된 엘리먼트.selection
객체는 사용자가 선택한 range
로 표현된다.
보통 한 개의 range를 갖고 있고 선택된 값은 selection
객체의 toString()을 통해 가져옴.
- 용어:
- 앵커: 셀렉션의 시작점
- 포커스: 셀렉션의 끝점
- 레인지: 문서에 인접한 부분
Range
노드와 텍스트 노드를 포함한 문서의 일부. (=문서의 특정 부분)
- 레인지 생성 방법:
- document.craeteRange()
- Selection 객체의 getRangeAt()
- Range() 생성자