:: Dev/Etc

[Javascript] 클립보드로 복사하기

jETA 2015. 8. 21. 15:44
반응형

Clipboard를 통한 공격이 가능함이 알려진 뒤 소위 Modern Browser에서는

Clipboard에 대한 Sandbox 정책을 적용한 것으로 알고 있다.


이를 우회하기 위해 아래 방법을 활용할 수 있다.


function copy2clipboard(text) {
	// 최신 브라우저에서도 복사되도록 함
	var textArea = document.createElement("textarea");

	// 임시로 textarea 생성
	textArea.style.position = 'fixed';
	textArea.style.top = 0;
	textArea.style.left = 0;
	textArea.style.width = '2em';
	textArea.style.height = '2em';
	textArea.style.padding = 0;
	textArea.style.border = 'none';
	textArea.style.outline = 'none';
	textArea.style.boxShadow = 'none';
	textArea.style.background = 'transparent';
	textArea.value = text;
	document.body.appendChild(textArea);

	// text를 넣은 후 선택
	textArea.select();

	// 복사 시도
	try {
		var successful = document.execCommand('copy');
		if(successful) alert("주소가 복사되었습니다.");
	} catch (err) {
		console.log('Unable to copy');
	}

	// textarea 삭제
	document.body.removeChild(textArea);
}


복사할 문자열을 매개변수로 받아서, 임시로 textarea를 생성한 뒤

복사 후, 다시 textarea를 삭제하는 방식이다.


일종의 우회 방식이기 때문에, 일부 환경에서나 추후 제대로 작동하지 않을 수 있다.

반응형