Jump to content

User:Opencooper/svgReplace.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Opencooper (talk | contribs) at 07:06, 12 September 2017 (rewrite to actually get the file link from the commons API). 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.
// Warning: does not check for browser SVG support;
//          Also downloads SVG files in addition to PNGs, so shouldn't be used
//          by the bandwidth-conscious
// This script relies on the current HTML output by MediaWiki. It could change
// in the future, see https://phabricator.wikimedia.org/T118517 for example.
// The Imageinfo property will also eventually be superseded.
function getLink() {
    if (!(mw.config.get('wgAction') === 'view'
          && mw.config.get('wgIsArticle'))) {
        return;
    }
	
	alert("ran");
	
    $("#bodyContent .image").each(function() {
        var imgLink = $(this).attr("href");
        
        // If it's not an svg, skip it
        if (!/.*\.svg/.test(imgLink)) {
            return true;
        }
        
        // Get the filename
        var fileMatch = /File:.*/.exec(imgLink);
        if (fileMatch) {
            fileName = fileMatch[0];
        } else {
            throw new Error("Filename could not be parsed.");
        }

        // Query the Commons API for the SVG link
        // API docs: https://www.mediawiki.org/wiki/API:Imageinfo
        $.ajax({
            url: "https://commons.wikimedia.org/w/api.php",
            data: {
            	action: "query",
            	format: "json",
            	titles: fileName,
            	prop: "imageinfo",
            	iiprop: "url",
            	origin: "*"
            },
            success: replaceSvg
        });
    });
}

function replaceSvg(response) {
	// Parse JSON
	var filepageId = Object.keys(response.query.pages)[0];
	var url = response.query.pages[filepageId].imageinfo[0].url;
	
	// Change the source in the child <img> element
    $(this).children().attr("src", url);
}

$(getLink);