How to get URLs in JavaScript for uploaded files in MediaWiki

Today, I was trying to remove hard-coded paths from some JS code.

In my particular case, I started with a stem that looked like this:


But MediaWiki provides different ways to configure it to serve images.

The hard-coded url wouldn’t work in a wiki that had $wgHashedUploadDirectory set to false. And it wouldn’t work in a wiki where img_auth.php wasn’t being used.

I wanted to be able to provide the client-side with a URL that would display the image in the file Logo.png no matter how the wiki was configured.

I thought someone else might have a clue, so I asked in the MediaWiki Extensions room on Matrix. Marijn told me about the little known Special:Filepath (or Special:Redirect/file) special page that would do this.

After a little testing, it worked. A bit of JQuery and MW.js and I have the following that provides the client with the appropriate url path regardless of the wiki’s configuration:

var url=mw.util.getUrl("Special:Redirect/file/Logo.png");
$("#image-here").append("<img src='" + url + "' />");

Image credit: Tomas Castelazo, CC BY-SA 3.0, via Wikimedia Commons

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: