如何在 MediaWiki 中使用 javascript 检测重定向
How to detect a redirect with javascript in MediaWiki
我想检测 MediaWiki 中的 URL 是否指向重定向。当我 运行 在 en.wikipedia.org 上执行以下脚本时:
let test = await fetch('https://en.wikipedia.org/wiki/Bruce_Wayne');
console.log(test.url); // → https://en.wikipedia.org/wiki/Bruce_Wayne
console.log(test.redirected); // → false
然而,当我在地址栏中输入 https://en.wikipedia.org/wiki/Bruce_Wayne
时,我被重定向到 https://en.wikipedia.org/wiki/Batman#Bruce_Wayne
。
如果 Url 被重定向到不同的文档,我如何使用 JavaScript 进行检测?我可以在不获取整个文档的情况下找出答案吗?
请参阅 Response.redirected and Response.url 关于检测重定向的文档。
您可以发出 HEAD 请求以避免获取整个文档。不过,它会在 cross-domain 请求上触发 CORS 行为。您也可以使用维基百科的 API 来查看页面是否是重定向,而不是获取页面,但它可能会更慢,并且服务器的负载会更大——维基百科针对正常的页面浏览量进行了高度优化。
您可以尝试单独请求 wiki API,例如:https://en.wikipedia.org/w/api.php?action=query&titles=Wikipedia:!--&redirects&format=json&formatversion=2。
结果将是:
{
"batchcomplete": true,
"query": {
"redirects": [
{
"from": "Wikipedia:!--",
"to": "Wikipedia:Manual of Style",
"tofragment": "Invisible comments"
}
],
"pages": [
{
"pageid": 33697,
"ns": 4,
"title": "Wikipedia:Manual of Style"
}
]
}
}
注意 query.redirects
部分。
示例取自 https://www.mediawiki.org/wiki/API:Query#Resolving_redirects.
我想检测 MediaWiki 中的 URL 是否指向重定向。当我 运行 在 en.wikipedia.org 上执行以下脚本时:
let test = await fetch('https://en.wikipedia.org/wiki/Bruce_Wayne');
console.log(test.url); // → https://en.wikipedia.org/wiki/Bruce_Wayne
console.log(test.redirected); // → false
然而,当我在地址栏中输入 https://en.wikipedia.org/wiki/Bruce_Wayne
时,我被重定向到 https://en.wikipedia.org/wiki/Batman#Bruce_Wayne
。
如果 Url 被重定向到不同的文档,我如何使用 JavaScript 进行检测?我可以在不获取整个文档的情况下找出答案吗?
请参阅 Response.redirected and Response.url 关于检测重定向的文档。
您可以发出 HEAD 请求以避免获取整个文档。不过,它会在 cross-domain 请求上触发 CORS 行为。您也可以使用维基百科的 API 来查看页面是否是重定向,而不是获取页面,但它可能会更慢,并且服务器的负载会更大——维基百科针对正常的页面浏览量进行了高度优化。
您可以尝试单独请求 wiki API,例如:https://en.wikipedia.org/w/api.php?action=query&titles=Wikipedia:!--&redirects&format=json&formatversion=2。 结果将是:
{
"batchcomplete": true,
"query": {
"redirects": [
{
"from": "Wikipedia:!--",
"to": "Wikipedia:Manual of Style",
"tofragment": "Invisible comments"
}
],
"pages": [
{
"pageid": 33697,
"ns": 4,
"title": "Wikipedia:Manual of Style"
}
]
}
}
注意 query.redirects
部分。
示例取自 https://www.mediawiki.org/wiki/API:Query#Resolving_redirects.