User:Opencooper/svgReplace.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
![]() | This user script seems to have a documentation page at User:Opencooper/svgReplace. |
// 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);