Differentiate between current domain and domain of requested image
I want to be able to differentiate between images requested from the current domain and from external domains to deal with canvas and cross domain requests. I am currently proxying all absolutely sourced images and not proxying local ones using
if ( $(this).attr('src').substr(0, 4) == 'http') { …
However, this is obviously inefficient. What is the best way to differentiate between images on the current domain and those on another domai开发者_运维百科n?
You can test the hostname of the image src against what is in the address bar, like this:
var hostname = window.location.hostname;
$.each('img', function(){
if (hostname !== $(this).attr('src'))
{
$(this).attr('src', 'something-else');
}
});
This is assuming jQuery. You will probably need to tweak hostname / img src or substring them to get the bit you want to test against.
Further reading: http://www.w3schools.com/jsref/obj_location.asp
Thanks to rsplak, Felix Kling and jammypeach I got there. My solution for anyone else:
if (window.location.hostname !== this.src.split('/')[2]) { ...
The above statement will only evaluate as true if the image is hosted on a different domain solving the problem.
精彩评论