Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client side - How do I get the "Location" header of any website?

Tags:

javascript

Before you say that this isn't possible, please refer to here. All I need is to stop the redirecting of a automatic redirect url, and get the page that it is trying to redirect to. I prefer the "Position" header, but if there is another way, that would be great.

It doesn't seem like XMLhttpRequest will work, as to send a request, the url has to be on the same domain, which isn't this case. Please help!!!

like image 491
Dalrae Avatar asked Sep 01 '25 23:09

Dalrae


1 Answers

It looks like hurl.it doesn't use XMLHttpRequest, instead they make their own request (server-side) which does let them choose to follow redirections or not (for example, .NET's HttpWebRequest.AllowAutoRedirect property).

Whereas in client JavaScript you have to use XMLHttpRequest and unfortunately there is no API to disable redirects.

However there is a new Web API called Fetch - supported by Chrome since 42, Edge since release 14, and partial support in Firefox since release 39.

With Fetch you can choose to not follow redirects, like so:

var url = "http://assetgame.roblox.com/asset/?id=1818";
var fetchOptions = {
    redirect: 'manual' // use "manual" to disable the automatic following of redirections
};
var request = new Request( url, fetchOptions );

window
    .fetch( request )
    .then( function( response ) {

        alert( response.headers.get('Location') );

    } );

This can be put more succinctly:

fetch( "http://assetgame.roblox.com/asset/?id=1818", { redirect: 'manual' } )
    .then( res => alert( res.headers.get('Location') ) );

UPDATE:

According to the documentation, the Location header will not be exposed to clients, unfortunately:

http://xcatliu.com/fetch/#atomic-http-redirect-handling
Throughout the platform, redirects (a response whose status or internal response's (if any) status is a redirect status) are not exposed to APIs. Exposing redirects might leak information not otherwise available through a cross-site scripting attack.

So only value added by the Fetch API is a more succinct request/response API, and the ability to detect redirections and choose to not follow them (unlike XMLHttpRequest which will always follow redirections), but you can't get the raw header, unfortunately.

Note that WebSockets do not expose a true TCP socket connection, so you cannot connect to arbitrary network services using WebSockets either.

like image 148
Dai Avatar answered Sep 03 '25 13:09

Dai