In my web application, users can post text to a feed, and the text may include URL's. My code scans for URL's and replaces them which anchor tags pointed at the URL's. I want to change this so that my code can detect whether or not the URL points to an image, and if it does, render an image tag inside the anchor tag, instead of just the URL text.
I can do this on server side code by sending a quick 'HEAD' request to the URL to see what the Content-Type is on the response, and this works reliably. However, it doesn't scale well for obvious reasons.
What would be better is if I could push this logic onto the client's browser. I'd like to use JavaScript + jQuery to send the 'HEAD' request to the specified URL, and read the Content-Type header from the response.
I know that cross-domain requests are an issue. Could I somehow use JSONP? What options do I have?
I got some good answers to my question, but I wanted to point out something in big bold letters. As Adam pointed out in the comments, this is a security risk. If you can guarantee the URL's of the images are all coming from trusted domains, you're good to go with this solution. However, in my scenario, users can enter whatever URL they want. This means they could create their own site which requires basic authentication, and then when the jQuery runs to set the src attribute on the created image, the user is presented with a username/password dialog, and that's obviously a huge risk.
You can try to load it in a hidden img element:
$('<img />').attr('src', url).load(function () {
alert('url contains an image');
}).error(function () {
alert('url is no image');
});
you can create a javascript Image
object you will try loading all the links like this:
myImageObject = new Image();
// handle an URL
myImageObject.onload = function(e) {
alert('it is an image');
}
myImageObject.src = 'http://www.google.bg/images/srpr/logo3w.png';
jsFiddle example
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