如何将自定义全局JavaScript添加到MediaWiki [英] How to add custom global javascript to mediawiki

查看:147
本文介绍了如何将自定义全局JavaScript添加到MediaWiki的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将自定义javascript文件(例如custom.js)添加到MediaWiki安装中?

例如,如果将custom.js放在文件夹resources/lib/下,如何将其加载到每一页上?

我不打算将其作为扩展的一部分,而我希望将所做的更改保留在LocalSettings.php中.

解决方案

正如garryp所建议的那样,您可以将JavaScript代码放入 MediaWiki:Common.js页面.

仅当启用 $ wgUseSiteJs 时,才会加载Common.js的JavaScript代码.但是,这是默认设置,因此除非您通过在LocalSettings.php文件中添加$wgUseSiteJs = false;这样的行来故意禁用它,否则它应该起作用.


也可以使用 ResourceLoader 从文件中加载JavaScript代码,但这有点复杂. .还是作为一个简单的例子,如果您在主MediaWiki目录中有名为foo/bar.jsfoo/baz.js的文件,则可以通过将以下代码添加到LocalSettings.php文件中来加载它们:

 // register a ResourceLoader module...
$wgResourceModules['custom.foo.whatever'] = array(
    'scripts' => array( 'foo/bar.js', 'foo/baz.js' ),
    // could e.g. add dependencies on core modules here
);
// ...and set up a hook to add it to every page
function addMyCustomScripts( &$out ) {
    $out->addModules( 'custom.foo.whatever' );
    return true;
}
$wgHooks['BeforePageDisplay'][] = 'addMyCustomScripts';
 

基本上,此方法对扩展作者最有用,他们可以根据需要使用它来加载CSS和JS代码. 请参见 $ wgResourceModules 解决方案

As garryp has already suggested, you can put the JavaScript code into MediaWiki:Common.js. Note that this is not a file, but simply a page you can edit (as an administrator) on your wiki. For example, here's the MediaWiki:Common.js page on the English Wikipedia.

JavaScript code from Common.js is only loaded if the $wgUseSiteJs is enabled. However, this is the default setting, so it should work unless you've deliberately disabled it by adding a line like $wgUseSiteJs = false; into your LocalSettings.php file.


It's also possible to load JavaScript code from a file using ResourceLoader, but this is a bit more complicated. Still, just as a quick example, if you had, say, files named foo/bar.js and foo/baz.js in your main MediaWiki directory, you could load them by adding the following code into your LocalSettings.php file:

// register a ResourceLoader module...
$wgResourceModules['custom.foo.whatever'] = array(
    'scripts' => array( 'foo/bar.js', 'foo/baz.js' ),
    // could e.g. add dependencies on core modules here
);
// ...and set up a hook to add it to every page
function addMyCustomScripts( &$out ) {
    $out->addModules( 'custom.foo.whatever' );
    return true;
}
$wgHooks['BeforePageDisplay'][] = 'addMyCustomScripts';

Basically, this method is mostly useful for extension authors, who can use it to load CSS and JS code as needed. See the $wgResourceModules and BeforePageDisplay documentation for more details, including additional module options (and core modules).

这篇关于如何将自定义全局JavaScript添加到MediaWiki的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆