Pierre
Pierre

Reputation: 6172

Is it possible to observe 302 redirects with javascript?

Is there, with Javascript, a way to monitor URL changed via 302 redirects on the elements in page?

I have some script on a remote server I don't have control on, loaded via the script tag, which may, in certain circumstances, immediately return a 302 redirect to another location.

Is it a way to observe this redirect, and to be notified of the new location, to take different actions depending on the loaded URI?

Upvotes: 4

Views: 4512

Answers (2)

nwellcome
nwellcome

Reputation: 2299

The common wisdom here seems to be no, but if you wanted to test it out try loading the script with jQuery's ajax:

var redirected = false;
$.ajax({
    url: url,
    dataType: "script",
    statusCode: {
        302: function() {
            redirected = true;
        }
    },
    success: function () {
        if (redirected) {
            // something
        } else {
            // something else
        }
    }
});

note that the script will already have run by the time you get to the success function, so this might be of no use at all even if it works.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074276

I don't think so. The draft spec from the W3C says an XMLHttpRequest would transparently follow the redirect, and you're not even using something that gives you that much visibility on the process when you're just adding a script element to the page (heck, you're lucky to get load / onreadystate events from it).

Upvotes: 0

Related Questions