Can user's custom JavaScript on MediaWiki call a Lua module?

624 views Asked by At

On MediaWiki wikis each user has a user JavaScript page they can put code in, much like GreaseMonkey but without extensions. Such as at User:YourUsername/vector.js

MediaWiki has also had an embedded Lua, called Scribunto, for a little while now.

I know Lua modules can be called from MediaWiki templates, and I suppose that's their main use. But Googling and hunting around the MediWiki docs I can't find whether there's a way to call a Lua module from your user JavaScript.


(I need to map names of languages to language codes in my JS and there's a Lua module to do just that without me duplicating the code (mainly data) in a second language.)

1

There are 1 answers

1
svick On BEST ANSWER

You can't do this directly, because JS runs on the client and Lua on the server. What you can do is to use the MediaWiki API from JS to invoke the module. Specifically using the expandtemplates API module.

For example, if you wanted to call the function h2d from Module:Hex with the parameter FF ({{#invoke:hex|h2d|FF}} in wikitext) and alert the result, then the JS would look like this:

var api = new mw.Api();
api.get( {
    action: 'expandtemplates',
    text: '{{#invoke:hex|h2d|FF}}'
} ).done ( function ( data ) {
    alert(data.expandtemplates['*']);
} );

And for the OP's specific case, running on the English Wiktionary:

var langName = 'Esperanto';
(new mw.Api()).get({
  action: 'expandtemplates',
  format: 'json',
  prop: 'wikitext',
  text: '{{#invoke:languages/templates|getByCanonicalName|' + langName + '|getCode}}'
}).done(function(data) {
  alert('Language name: ' + langName + '\nLanguage code: ' + data.expandtemplates.wikitext);
});

(prop: 'wikitext' avoids a warning from the API and lets you access the result as data.expandtemplates.wikitext rather than the slightly mystifying data.expandtemplates['*']. Otherwise there's no difference.)