Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get final url from XHR object after redirect

Suppose I use ajax (e.g. via jQuery) to do POST request to an API that implements a PRG pattern. Hence it will redirect me:

POST /some/api
HTTP/1.1 303 See Other
Location: /some/other/location

jQuery will then automatically follow the redirect and perform a:

GET /some/other/location

And then call the response handlers (success, failure, etc) with the output from the latter request. However, how can I read the location of the final resource (/some/other/location in this case) in javascript?

like image 342
Jeroen Ooms Avatar asked May 08 '13 00:05

Jeroen Ooms


2 Answers

While this is an old post, hopefully this updated (2018) answer will help someone. Note that this solution does not work in Internet Explorer (any version), and only works in relatively modern versions of other browsers.

XMLHttpRequest now exposes a read-only property called responseURL, which returns the URL of the response after any redirects have occurred.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com', true);
xhr.onload = function () {
  console.log(xhr.responseURL); // Prints http://example.com
};
xhr.send();

See docs at https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseURL

like image 99
Fred Vollmer Avatar answered Sep 20 '22 04:09

Fred Vollmer


As far as I know, it's not possible with the XMLHttpRequest object. But, if you're operating within your [trusted] domain, and if it's important information, you could use an iframe instead:

var hidden_iframe = document.createElement('iframe');
hidden_iframe.name = 'hidden_iframe';
hidden_iframe.style.display = 'none';
hidden_iframe.onload = function() {
  console.log(hidden_iframe.contentWindow.location.toString());
}
document.body.appendChild(hidden_iframe);

var request = document.createElement('form');
request.method = 'post';
request.action = '/some/api';
request.target = 'hidden_iframe';
request.style.display = 'none';

// append INPUTs to the request form here

document.body.appendChild(request);
request.submit();

Your console should report 1 or more URLs, the last of which will be:

http(s)://{yourdomain}/some/other/location

like image 42
svidgen Avatar answered Sep 21 '22 04:09

svidgen