Search code examples
javascriptjquerycorsxmlhttprequest

Trouble on checking of image existing on remote server in Chrome browser by using XMLHttpRequest


I use this JQuery method on page to check if image exists:

function imageExists(imageUrl) {
  var http = new XMLHttpRequest();
  http.open('HEAD', imageUrl, false);
  http.send();
  return http.status !== 404;
} 

If I load the page in browser, it works great, but if I go to the next page and then go back to this page the script does not work correctly. There is error in browser console:

Access to XMLHttpRequest at 'https://server/image.jpg' from origin 'http://client' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This error occurs only when I back from another site page to this page in Chrome browser. There is no error in Firefox and Edge browsers

Thanks!!!


Solution

  • This issue has been fixed by adding request header of 'Cache-Control' with 'no-cache' value:

    function imageExists(imageUrl) {
        var http = new XMLHttpRequest();
    
        http.open('HEAD', imageUrl, false);
        http.setRequestHeader('Cache-Control', 'no-cache');
        http.send();
    
        return http.status !== 404;
    }