如何将自定义全局JavaScript添加到MediaWiki [英] How to add custom global javascript to 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.js
和foo/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 和核心模块).
How can I add a custom javascript file (let's say custom.js
) to a mediawiki installation?
For instance, if I put custom.js
under the folder resources/lib/
, how do I get that to be loaded on every page?
I am not trying to do this as part of an extension, and I would prefer to keep my changes in LocalSettings.php
.
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屋!