User:喵/langlinks replace.js
< User:喵
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
// To apply this script on the current article, open the EDIT page of the article, and use this bookmarklet:
// javascript:importScriptURI("https://zh.wiki.x.io/w/index.php?title=User:%E5%96%B5/langlinks_replace.js&action=raw");
// After quries, the wikilinks in the editbox will be replaced by its corresponding article in ZHWP.
// Please do NOT save the replaced article. Instead, copy the content to ZHWP.
// <nowiki>
(function (mw, $) {
var api = new mw.Api();
var wlregex = /\[\[([^:|\]]+)(\|[^\]]*)?\]\]/g;
var map = {};
var requests = [];
var current = 0;
var textbox = $('#wpTextbox1');
var wikitext = textbox.val();
if (textbox.length == 0) {
alert('This script must be run on the EDIT page.');
return;
}
var request_langlink = function (articles, opt_llcontinue) {
return api.get({
action:'query',
rawcontinue:'',
titles: articles.join('|'),
prop:'langlinks',
redirects: 'follow',
lllimit:'500',
llcontinue: opt_llcontinue
});
};
var query_complete = function (data) {
var pages = data["query"]["pages"];
for (var p in pages)
{
var ll = pages[p]["langlinks"];
for (var i in ll) {
if (ll[i]["lang"] == "zh") {
map[pages[p]["title"]] = ll[i]["*"];
}
}
}
var redirects = data["query"]["redirects"];
if (redirects) {
for (var i in redirects) {
map[redirects[i]["from"]] = map[redirects[i]["to"]];
}
}
var norm = data["query"]["normalized"];
if (norm) {
for (var i in norm) {
map[norm[i]["from"]] = map[norm[i]["to"]];
}
}
if (data["query-continue"]) {
request_langlink(
requests[current],
data["query-continue"]["langlinks"]["llcontinue"]
).done(query_complete);
} else {
current++;
if (current >= requests.length) {
var result = wikitext.replace(
wlregex,
function (s) {
var q = /\[\[([^:|\]]+)(\|[^\]]*)?\]\]/g.exec(s);
var re = map[q[1]];
if (!re) return s;
return s.replace(q[1], re);
}
);
console.log(map);
$('#wpTextbox1').val(result);
alert("Done!");
} else {
request_langlink(requests[current]).done(query_complete);
}
}
};
var match = wlregex.exec(wikitext);
var t = [];
while (match != null) {
if (t.length == 50) {
requests.push(t);
t = [];
} else {
t.push(match[1]);
}
match = wlregex.exec(wikitext);
}
if (t.length > 0) {
requests.push(t);
}
request_langlink(requests[current]).done(query_complete);
})(mediaWiki, jQuery);
// </nowiki>