Šime Vidas
Šime Vidas

Reputation: 185933

How does this HTTP "redirect" work?

When I request this URL:

http://www.w3.org/TR/html5/embedded-content-1.html#the-img-element

the server responds with a 404 (File not found) HTTP-response. However, a few moments later a different URL is loaded into the browser, namely:

http://www.w3.org/TR/html5/the-img-element.html#the-img-element

The server basically sends a second HTTP-response whose URL is different from the URL that was originally requested.

enter image description here

How is this "redirect" possible? The first HTTP-response was a 404, not a 3xx. Afaik, 404 responses do not trigger a second HTTP-request by the browser. So, does the server just push the second response without any request being made? If yes, why does the browser allow that?


See for yourself: Open the "Net" tab of Chrome's dev tools, and make sure that the "Preserve Log upon Navigation" flag is activated. Now, load the first URL (from above).

Upvotes: 0

Views: 3087

Answers (1)

Šime Vidas
Šime Vidas

Reputation: 185933

Let me answer my own question here.

The second HTTP-request is initiated by JavaScript code that is executed as part of the page that was returned by the 404 response. That page contains:

<body onload="fixBrokenLink(404)">

and then:

function fixBrokenLink(is404) {
    if (window.location.hash.length < 1 && !is404)
        return;

    var fragid = window.location.hash.substr(1);
    if (fragid && document.getElementById(fragid))
        return;

    var script = document.createElement('script');
    script.src = 'fragment-links.js';
    document.body.appendChild(script);
}

I love how I've asked the question, made a comment on it, and then answered it, all without any participation from anyone else. :)

Upvotes: 1

Related Questions