0

I have a 2 hosts. The first one is for media files (mp3, mp4 and images) and the 2nd is where the site is. They are under 2 different domains (for example: https://example.com and https://files.example.com). There is a page where I have to check if a specific video (mp4 file) exists. I did it like that:

function CheckFileExists(url) {
    jQuery.ajax({
        url: url,
        dataType: "jsonp"
    }).done(function (data) {
        return true;
    }).fail(function (data) {
        return false;
    })
}

the dataType jsonp is set because it was the only way I've found to fix the "Access to XMLHttpRequest at 'https://files.example.com/videos/my_vid.mp4' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." problem. Without that parameter - the function always returns false.

Anyway, now there is another problem. the ajax call takes ages! it seems that it tries to load the entire video - which of course is not what I need.

Do you have any idea how to solve it?

  1. It must be a javaScript check and not in server side.
  2. The file domain is different then the site
  3. I only want to check if the file exist and not load the file

Thanks a lot!

Anne K
  • 9
  • 2
  • 1
    If you can, you could add the correct Access-Control-Allow-Origin header on the files so that you don't have CORS problems anymore, and using ajax, only make a [HEAD request](https://stackoverflow.com/questions/47240975/how-to-fetch-using-fetch-api-only-headers-in-javascript-not-the-whole-content) to get the headers back, not the whole file – blex Jun 26 '21 at 21:39
  • 1
    Do you have control of the software serving the files in the file domain? If so first step is to add a CORS header so that you can use something like `fetch()` which allows you to make a HEAD request. You can't make a HEAD request with jsonp. If you don't have control of the file domain then you must solve this server side - you can't solve this with javascript on the front-end if your file server don't return an Access-Control-Allow-Origin header – slebetman Jun 26 '21 at 21:58
  • 1
    There used to be a very good front-end only solution to this problem: use Adobe Flash to make a HEAD request for the file to avoid CORS issues. However modern browsers can no longer run Flash. It is also possible to do the same thing in Java. However modern browsers can also no longer run Java. – slebetman Jun 26 '21 at 22:00
  • Try this answer. Hopefully, it answers yours too. https://stackoverflow.com/questions/24296721/how-to-check-if-url-exists-using-javascript – hasbi Jun 26 '21 at 22:32

0 Answers0