사용자:하늘/addCopyButtonToCode.js

< 사용자:하늘
하늘 (토론 | 기여)님의 2023년 12월 30일 (토) 22:21 판

참고: 설정을 저장한 후에 바뀐 점을 확인하기 위해서는 브라우저의 캐시를 새로 고쳐야 합니다.

  • 파이어폭스 / 사파리: Shift 키를 누르면서 새로 고침을 클릭하거나, Ctrl-F5 또는 Ctrl-R을 입력 (Mac에서는 ⌘-R)
  • 구글 크롬: Ctrl-Shift-R키를 입력 (Mac에서는 ⌘-Shift-R)
  • 인터넷 익스플로러 / 엣지: Ctrl 키를 누르면서 새로 고침을 클릭하거나, Ctrl-F5를 입력.
  • 오페라: Ctrl-F5를 입력.
function addCopyLinkToCodeElements() {
	mw.util.addCSS('.copy-button { 	margin-top: 0.7em; margin-right: 0.7em; position: absolute; z-index: 100; right: 0; }\
	.mw-highlight { position: relative; }');
	
	const highlightElements = document.querySelectorAll(".mw-parser-output .mw-highlight");
	
	highlightElements.forEach(element => {
		var copybutton = new OO.ui.ButtonWidget({
			label: 'copy',
			icon: 'code',
			title: 'copy',
			classes: ['copy-button']
		});
		const codeText = element.firstChild.innerText;
		copybutton.on('click', function () { copy(codeText); });
		const endBlock = document.createElement('div');
		endBlock.style = "clear:both";
		$(element).prepend(copybutton.$element);
		element.appendChild(endBlock);
	});
}

function copy(string) {
	navigator.clipboard.writeText(string);
}

mw.loader.using(['oojs-ui-core', 'oojs-ui.styles.icons-editing-advanced'], addCopyLinkToCodeElements);