Reputation: 345
Hi Unsplash allows to load random image from their website via:
https://source.unsplash.com/random/2560x1440
if I access the url from the browser each time the url generates random static image eg:
https://images.unsplash.com/photo-1488616268114-d949a6d72edf?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2560&h=1440&fit=crop&s=a7f66c8417bcf79d2503b84db64c7b1a
I would like to request the image in jquery or js via the first url and in response get the second one. Is this possible?
Upvotes: 6
Views: 7392
Reputation: 831
fetch('https://source.unsplash.com/random').then(res=>{console.log(res)})
from source worked for me.
Upvotes: 0
Reputation: 1
You can use PerformanceObserver
to get the name
property value of the requested resource
const key = "unsplash";
const url = `https://source.${key}.com/random/2560x1440`;
let bloburl = void 0;
let img = new Image;
const getResourceName = () => {
let resource = "";
const observer = new PerformanceObserver((list, obj) => {
// alternatively iterate all entries, check `"name"`
// property value for `key`, break loop if specific resource requested
for (let entry of list.getEntries()) {
let {name: res} = entry.toJSON();
resource = res;
}
});
observer.observe({
entryTypes: ["resource"]
});
return fetch(url)
.then(response => response.blob())
.then(blob => {
observer.disconnect();
bloburl = URL.createObjectURL(blob);
img.src = bloburl;
document.body.appendChild(img);
return resource
})
}
getResourceName().then(res => console.log(res)).catch(err => console.log(err))
You can alternatively use Response.url
const key = "unsplash";
const url = `https://source.${key}.com/random/2560x1440`;
let bloburl = void 0;
let img = new Image;
const getResourceName = fetch(url)
.then(response => Promise.all([response.url, response.blob()]))
.then(([resource, blob]) => {
bloburl = URL.createObjectURL(blob);
img.src = bloburl;
document.body.appendChild(img);
return resource
});
getResourceName.then(res => console.log(res)).catch(err => console.log(err))
Upvotes: 1
Reputation: 555
This is tricky since there are several things going on.
If you use Chrome or Firefox, open the developer tools and review the network tab you will see that the original request returns an HTTP 302 redirect to a different URL:
The browser then follows the specified Location
header and you get the page that you see. The image is within an <img>
on that page.
So to get the final image you need to:
img
tag.Good luck!
Upvotes: 1
Reputation: 116
You can use the responseURL of the XMLHttpRequest.
and this answer for an example in jQuery and native JS.
Upvotes: 2