hendry
hendry

Reputation: 10823

Find redirected img source

I have a URL to the latest Webcam shot http://cam.hackerspace.sg/last.jpg and it redirects to its source filename for example. 1364124301.jpg

I want to read the Epoch '1364124301' in Javascript so I can convert it to a timestamp. Though logging the img.src shows the old original URL. So how do I get '1364124301' without using Jquery?

Thanks!

Upvotes: 0

Views: 1574

Answers (2)

vuamitom
vuamitom

Reputation: 198

Using XMLHTTPRequest, you can read the newUrl after being redirected in XMLHTTPRequest.responseURL property. By comparing the newUrl with the originUrl, you can find out if it's a redirect.

Upvotes: 0

Michael Besteck
Michael Besteck

Reputation: 2423

Using JavaScript alone it seems impossible to get the redirect location: A XMLHTTPRequest hides the redirect transparently and an iframe does not allow to access it's URL if it's from another domain.

If you have a PHP enabled website the following will allow to get the redirect. (All code is without any capture of error conditions for simplicity, one will need to add error handling before using it).

First, to get the redirect location, some PHP, the file is called getRedirect.php:

<?php
$redirect = '';
$urlToQuery = $_GET['url'];
$urlParts = parse_url($urlToQuery);
$host = $urlParts['host'];
$path = $urlParts['path'];
$address = gethostbyname ($host);
$socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect ($socket, $address, 80);
$request = 'GET '.$path.' HTTP/1.1'."\r\n";
$request .= 'Host: '.$host."\r\n";
$request .= 'Connection: Close'."\r\n\r\n";
socket_write($socket, $request);
$answer = socket_read($socket, 8192);
socket_close($socket);
$answerLines = explode("\r\n", $answer);
foreach ($answerLines as $line) {
    $lineParts = explode(':', $line, 2);
    if($lineParts[0] == 'Location') {
    $redirect=trim($lineParts[1]);
    break;
    }
}
header('Content-Type: text/plain; charset=us-ascii');
header('Content-Length: '.strlen($redirect));
echo $redirect;
?>

Second, the image display page which uses JavaScript to set up the image and to query the redirect location (via XMLHTTPRequest to getRedirect.php):

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
    function updateImage() {
    var imgParent = document.getElementById("imgContainer");
    // delete existing image if exists
    var imgChild = imgParent.firstChild;
    if(imgChild!=null) imgParent.removeChild(imgChild);
    // insert new image with actual redirect
    var newImg = document.createElement("img");
    newImg.src = "http://cam.hackerspace.sg/last.jpg";
    imgParent.appendChild(newImg);
    var redirect = getRedirect("http://cam.hackerspace.sg/last.jpg");
    var timestamp = redirect.substring(redirect.lastIndexOf("/") + 1, redirect.lastIndexOf("."));
    document.getElementById("imageDate").innerHTML="Timestamp="+timestamp;

    }
    function getRedirect(url) {
    var redirect = "";
    var req = new XMLHttpRequest();
    req.open('GET', 'getRedirect.php?url='+url, false);
    req.onreadystatechange = function () {
        if (req.readyState == 4) {
        redirect = req.responseText;
        }
    };
    req.send(null);
    return redirect;
    }
</script>
</head>
<body>
<button onclick="updateImage();">update image</button>
<div id="imgContainer"></div>
<p id="imageDate"></p>
</body>
</html>

Upvotes: 2

Related Questions