Porting Wikidata Userscripts to Tampermonkey for use on other Wikibases

On Wikidata a number of very convenient user features are lacking from the core Wikibase codebase (e.g. Merge) and instead users have independently built these using Gadgets and Userscripts.

This is all well and good but it means that users on other Wikibases are then missing this functionality at all. They might try to copy these userscripts across but this brings issues with keeping the scripts and their modifications up to date. In fact the default setting for Mediawiki is to disable user js. This means that it’s not possible to simply copy the same works flow as on Wikidata (or Wikipedia, meta etc.). Finally even if this is possible these userscripts then do not work when logged out.

Luckily browser extensions for users to manage custom JS to modify sites have been around since 2004!

This post looks at the small amount of work necessary to port a userscript (like one might reference in their own common.js file on Wikidata) to a script the can be used with tampermoney; one of the more popular browser extensions for managing these userscripts.

How to install Tampermonkey

This is a browser extension available for both Chrome and Firefox. You can read the installation instructions here.

How to create a blank Tampermonkey script and set metadata

Click the new script button and fill in the details like the author. I like to credit the existing authors even if the license for the script I’m going to be including doesn’t require me to (for example it’s CC0).

How to adjust scripts written for MediaWiki to be injected by tampermonkey

Many MediaWiki userscripts rely on the window.MediaWiki object that is present very quickly after loading a page. Tampermonkey however immediately executes it’s script. Therefore it’s probably necessary to wrap the userscript you’ve copied from Wikidata in some logic to delay it’s execution until the MediaWiki object is available and it’s possible to use.

I’ve found a good starting point is as follows:

function waitForMediaWikiToExist(){
    if(typeof window.mw.loader.using !== "undefined"){
        <normal entry point here>
    }
    else{
        setTimeout(waitForMediaWikiToExist, 250);
    }
}

waitForMediaWikiToExist()

Adjust hardcoded values where necessary

This may mean removing explicit reference to Wikidata or things like namespace ids that may be wrong (e.g. 0 vs 120 for the item namespace which is the default).

Outcome

You can see an example of porting the previously mentioned Merge.js at this github gist.

Leave a Reply

Your email address will not be published. Required fields are marked *