User:Wctaiwan/rewritePathVariant.js
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
/**
* Work around https://phabricator.wikimedia.org/T223053 by rewriting link URLs
*
* Thanks to User:Legoktm for the idea and for technical assistance, and to
* User:Jack Phoenix for reviewing the implementation.
*/
(function ($, mw) {
'use strict';
if (mw.config.get('wgUserName') != null) {
return; // Don't run this on logged-in users
}
// Matches /zh-*/Foo and the variant query parameter in the current URL
var matchedPath = window.location.pathname.match(/^\/(zh-\w+)\//)
|| window.location.search.match(/[&?]variant=(zh-\w+)/);
if (matchedPath == null) {
return; // Path doesn't start with /zh-*/ or have a variant query paramter
}
var variant = matchedPath[1];
if (variant !== mw.config.get('wgUserVariant')) {
return; // Path variant doesn't match actual variant
}
// Rewrite /wiki/Foo links to /zh-*/Foo
// mousedown covers all click events (left/middle/right)
// touchstart is needed to handle "Open in Background" in Safari on iOS
$(document).on('mousedown keydown touchstart', 'a[href^="/wiki/"]', function() {
$(this).attr('href', function (_, originalPath) {
return originalPath.replace(/^\/wiki\//, '/' + variant + '/');
});
});
// Append &variant=zh-* to /w/index.php links
$(document).on('mousedown keydown touchstart', 'a[href^="/w/index.php?"]', function() {
$(this).attr('href', function (_, originalPath) {
if (originalPath.indexOf('variant=') !== -1) {
return originalPath; // Already has variant query parameter
}
var fragmentStart = originalPath.indexOf('#');
if (fragmentStart !== -1) {
return originalPath.slice(0, fragmentStart)
+ '&variant=' + variant
+ originalPath.slice(fragmentStart);
}
return originalPath + '&variant=' + variant;
});
});
})(jQuery, mediaWiki);