3

I need to programmatically check if a user can access YouTube, as YouTube is blocked in some parts of the world. I need to be able to do this in JavaScript.

What I have tried: 1) Creating an image dynamically and setting the source to be a known image on the YouTube domain - I ran into CORS issues here 2) Creating a simple GET request using XMLHttpRequest (same problem) 3) Looking at the YouTube API.. it does not appear to expose a method which can tell me whether a GET request was successful.. and of course, all calls are routed through https://www.googleapis.com/youtube/v3 which is not, strictly speaking, exactly the same as a request to http://www.youtube.com

Is there something obvious I'm missing here? Would appreciate any and all insight..

Thanks!

1 Answers1

1

CORS is a server-side header. If you're getting a CORS header, you're hitting Youtube's servers which are responding with response headers, which likely means that youtube is not "blocked".

So something like this should work just fine:

async function canAccessYoutube() {
      try {
        const request = await fetch(
          "https://www.youtube.com/",
          {
            mode: "no-cors"
          }
        );
        return true;
      } catch {
        return false;
      }
}

Assuming the blocking is DNS based, you can test the functionality by blocking Youtube on your own computer. If you have a mac or linux computer, add the following to your /etc/hosts file:

0.0.0.0 youtube.com
0.0.0.0 www.youtube.com
::0 www.youtube.com
::0 youtube.com

You may need to restart your computer for it to take effect.

Evan Conrad
  • 3,993
  • 4
  • 28
  • 46
  • I'm afraid I'm not getting a CORS header. I assumed this was because YouTube is not CORS enabled? if I sent a blank GET request from the site https://www.test-cors.org to http://www.youtube.com I get an XHR status of 0 which I take to mean the site is not CORS enabled. Please feel free to correct me if I'm wrong, this is a new area in my development. – aretheyalltaken Feb 07 '19 at 02:58
  • 1
    Hmm, I meant more "if you're running into CORS" problems, it means that you're actually hitting Youtube's servers, so your request has "succeeded". – Evan Conrad Feb 07 '19 at 03:02
  • Thanks for your help. The code you provided does indeed work well in Chrome but IE 11 is giving me some grief as it does not support Fetch, nor Promises. I need to sort that out separately but this is a step in the right direction. Thanks. – aretheyalltaken Feb 07 '19 at 05:41