Jump to content

User:Nardog/CopySectLink.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Nardog (talk | contribs) at 13:41, 5 June 2021. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
mw.config.get('wgNamespaceNumber') >= 0 &&
mw.config.get('wgAction') === 'view' &&
mw.config.get('skin') !== 'minerva' &&
$.when($.ready, mw.loader.using('mediawiki.util')).then(function copySectLink() {
	let handler = function (e) {
		e.preventDefault();
		let text = (mw.config.get('wgPageName') + (
			this.hash
				? '#' +
					this.parentElement.parentElement.querySelector('.mw-headline').id.replace(
						/[\[\]\{\|\}]/g,
						s => '&#' + s.codePointAt(0) + ';'
					)
				: ''
			)).replace(/_/g, ' ');
		navigator.clipboard.writeText(text).then(() => {
			mw.notify(`Copied "${text}"`);
		}, () => {
			let $input = $('<input>', {
				type: 'text',
				value: text,
				readonly: '',
				style: 'position:absolute;left:-999px'
			}).appendTo(document.body);
			$input[0].select();
			document.execCommand('copy');
			$input.remove();
			mw.notify(`Probably copied "${text}"`);
		});
	};
	let url = mw.util.getUrl(mw.config.get('wgPageName'));
	document.querySelectorAll('#firstHeading, .mw-headline').forEach(el => {
		let isFirst = el.tagName === 'H1';
		let hn = isFirst ? el : el.parentElement;
		let bracket = hn.querySelector('.mw-editsection-bracket:last-child');
		if (bracket) {
			$(bracket).before(' | ');
		} else {
			bracket = $('<span>').addClass('mw-editsection').append(
				$('<span>', { class: 'mw-editsection-bracket', text: '[' }),
				$('<span>', { class: 'mw-editsection-bracket', text: ']' })
			).appendTo(hn).children().last()[0];
		}
		$('<a>', {
			class: 'copysectlink',
			href: url + (isFirst ? '' : '#' + el.id),
			text: 'copy'
		}).click(handler).insertBefore(bracket);
	});
});