difference between youtube's request and mine

254 Views Asked by At

i want to make a script that makes every video's comment section look like the ones that still have the old kind. for example, videos on this channel:https://www.youtube.com/user/TheMysteryofGF/videos in Firebug, in the Net tab, i noticed the comment JSON file's URL it is requested from is different. i tried to run a code on the youtube watch page which would request the file the same way, but it doesnt work, and in firebug it says it was forbidden. the URL is the same, they are both POST, and i cant figure out what is different. i can even resend the original request in firebug and it works... so anyway, here is a code i tried on a video with "1vptNpkysBQ" video url.

var getJSON = function(url, successHandler, errorHandler) {
  var xhr = typeof XMLHttpRequest != 'undefined'
    ? new XMLHttpRequest()
    : new ActiveXObject('Microsoft.XMLHTTP');
  xhr.open('post', url, true);
  xhr.onreadystatechange = function() {
    var status;
    var data;
     // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
    if (xhr.readyState == 4) { // `DONE`
      status = xhr.status;
      if (status == 200) {
        data = JSON.parse(xhr.responseText);
        successHandler && successHandler(data);
       } else {
        errorHandler && errorHandler(status);
      }
    }
  };
  xhr.send();
};

getJSON('https://www.youtube.com/watch_fragments_ajax?v=1vptNpkysBQ&tr=time&frags=comments&spf=load', function(data) {
  alert('Your public IP address is: ' + data);
}, function(status) {
  alert('Something went wrong.');
});
1

There are 1 best solutions below

3
On

You are using Ajax to get data. Ajax has 1 restriction: You can only get data from your own server. When you try to get data from another server/domain, you get a "Access-Control-Allow-Origin" error.

Any time you put http:// (or https://) in the url, you get this error.

You'll have to do it the Youtube way.


That's why they made the javascript API. Here is (the principal of) how it works. You can link javascript files from other servers, with the < script > tag

So if you could find a javascript file that starts with

var my_videos = ['foo', 'bar', 'hello', 'world'];

then you can use var my_videos anywhere in your script. This can be used both for functions and for data. So the server puts this (dynamically generated) script somewhere, on a specific url. You, the client website can use it.

If you want to really understand it, you should try building your own API; you'll learn a lot.


Secondary thing: Use GET.

POST means the client adds data to the server (example: post a comment, upload a file, ...). GET means you send some kind of ID to the server, then the server returns its own data to the client.

So what you are doing here, is pure GET.