This question is not a duplicate of one of the above mentioned, since I have no control over the server response as it is the case in the other two questions above.
I use $.get
to load the content of an external document into the current website.
However, I need the final URL of this external document. In the case, where the original URL gets redirected (302) to a different URL, I need the new URL.
Can I get the final URL from the loaded document (after 302 redirect) using the jQuery $.get
method?
Based on the feedback below, I updated my code to this, but I still don't get the final URL:
$.get(url, function(html, status, xhr){
console.log(xhr.getResponseHeader('TM-finalURL')); // result: null
});
Logging all response headers with xhr.getAllResponseHeaders()
gives me (for a page with 302 redirect) the following result:
Pragma: no-cache
Date: Fri, 28 Feb 2014 15:30:22 GMT
Server: Apache
X-Powered-By: PHP/5.3.28
Transfer-Encoding: chunked
Content-Type: text/html
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection: Keep-Alive
Keep-Alive: timeout=15, max=100
Expires: Thu, 19 Nov 1981 08:52:00 GMT
But no final URL. Did I understand something wrong here?
Looking at the XHR specification, you can see that it is not built to be flexible. All redirects are handled transparently:
If the response has an HTTP status code of 301, 302 ... transparently follow the redirect
No events are ever triggered in JavaScript with the intermediate status codes. JavaScript will only be notified of the final HTTP status and the data returned, as this is what is supposed to be made available:
Once all HTTP headers have been received, the synchronous flag is unset, and the HTTP status code of the response is not one of 301, 302, 303, 307, and 308
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With