简体   繁体   中英

How to detect a redirect with javascript in MediaWiki

I'd like to detect if a URL in a MediaWiki points to a redirect. When I run the following script on 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

yet when I enter https://en.wikipedia.org/wiki/Bruce_Wayne into the address bar I get redirected to https://en.wikipedia.org/wiki/Batman#Bruce_Wayne instead.

How can I detect with JavaScript if a Url gets redirected to a different document? And can I find out without fetching the whole document?

See the documentation of Response.redirected and Response.url on detecting redirects.

You can make a HEAD request to avoiding fetching whole documents. It will trigger CORS behavior on cross-domain requests though. You could also use Wikipedia's API to see if a page is a redirect, instead of fetching the page, but chances are it will be slower for you and more load for the server - Wikipedia is highly optimized for normal pageviews.

You can try a sepatate request to wiki API, eg: https://en.wikipedia.org/w/api.php?action=query&titles=Wikipedia:!--&redirects&format=json&formatversion=2 . Result will be:

{
    "batchcomplete": true,
    "query": {
        "redirects": [
            {
                "from": "Wikipedia:!--",
                "to": "Wikipedia:Manual of Style",
                "tofragment": "Invisible comments"
            }
        ],
        "pages": [
            {
                "pageid": 33697,
                "ns": 4,
                "title": "Wikipedia:Manual of Style"
            }
        ]
    }
}

Note the query.redirects part. Examples are taken from https://www.mediawiki.org/wiki/API:Query#Resolving_redirects .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM