Jump to content

User:Rummskartoffel/share ExpandTemplates url.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.
mw.loader.using(["oojs-ui", "mediawiki.util"], function() {
    if (mw.config.get("wgCanonicalSpecialPageName") !== "ExpandTemplates")
        return;
    new OO.ui.ButtonWidget({
        label: "Copy URL",
        href: "#",
    })
    .on("click", function() {
        const form = $(".mw-htmlform").get(0);
        const url = new URL(mw.util.getUrl("Special:ExpandTemplates"), location);
        ["wpContextTitle", "wpInput"].forEach(
            param => url.searchParams.set(param, form.elements[param].value)
        );
        [
            "wpRemoveComments", 
            "wpRemoveNowiki", 
            "wpGenerateXml", 
            "wpGenerateRawHtml"
        ].forEach(
            param => url.searchParams.set(
                param,
                Number(OO.ui.infuse($(`[name="${param}"]`).parent()).isSelected())
            )
        );
        try {
            navigator.clipboard.writeText(url)
            .then(() => mw.notify("Link copied to clipboard"))
            .catch(err => {
                console.warn(err);
                copyFallback(url);
            });
        } catch (err) {
            console.warn(err);
            copyFallback(url);
        }
    })
    .$element.appendTo(".mw-htmlform-submit-buttons");
    
    function copyFallback(text) {
    	const input = $("<input>", {
    		value: text,
    		type: "text",
    		style: "position: fixed; top: -100em;"
    	})
    	.appendTo("body").select();
    	document.execCommand("copy");
    	input.remove();
    	mw.notify(
    		"Warning: Falling back to old method of clipboard access. Copying to clipboard may have failed.", {
    			type: "warn"
    		}
    	);
    }
});