Jump to content

User:Nardog/TemplatePreviewGuard.js

From Wikipedia, the free encyclopedia
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.
['edit', 'submit'].includes(mw.config.get('wgAction')) &&
$(function templatePreviewGuard() {
	let button = document.querySelector('input[name="wpTemplateSandboxPreview"]');
	if (!button) return;
	let proceed;
	button.addEventListener('click', e => {
		if (proceed) {
			proceed = false;
			return;
		}
		e.preventDefault();
		e.stopPropagation();
		let formData = new FormData(button.form);
		let page = formData.get('wpTemplateSandboxPage');
		let temp = formData.get('wpTemplateSandboxTemplate');
		if (!page || !temp) return;
		mw.loader.using('mediawiki.api').then(() => (
			new mw.Api().get({
				action: 'query',
				titles: page,
				prop: 'templates',
				tltemplates: temp,
				formatversion: 2
			})
		)).always(response => {
			if (((((response || {}).query || {}).pages || [])[0] || {}).templates ||
				confirm(`"${page}" doesn't appear to transclude "${temp}". Continue?`)
			) {
				proceed = true;
				button.click();
			}
		});
	}, true);
});