Saturday, September 6, 2008

How to download Youtube Videos using Javascript?

You can use Javascript and AJAX technologies to download Youtube videos on your web page that is all client based solution. I have outlined the steps to extract the values needed to form the URL to download the Youtube videos.

First we should know Youtube download URL summary:
Youtube videos can be downloaded from the URL All we need are the values of video_id, l , t, and sk. My script extracts these values from Youtube's HTML page.

The summary of the script:
Download the source of the page of the URL
VDAGIFjt6m4 is the ID of a video). Look for a particular pattern in the source. Once the pattern is extracted convert it into JSON format. From the JSON data walk through and get the values of id, l, t, and sk.

More detailed algorithm.
1) Get the page source from Youtube using the public URL -
In the example VDAGIFjt6m4 is the ID. The ID can change depending upon your video.

2) The source will be entire page which has the Youtube video embedded we are only interested in the following HTML -
var swfArgs = {"BASE_YT_URL": "", "vq": null, "sourceid": "y", "video_id": "VDAGIFjt6m4", "l": 65, "sk": "mkKFIRWXheJgUGsaU6Bx2LsnWvZldVraC", "fmt_map": "6/720000/7/0/0", "t": "OEgsToPDskK0DEe01pPPKzJJ700ykmac", "hl": "en", "plid": "AARWNMbnD8zgFCZ0AAAAoAAYAAA", "sdetail": "p%3A/"};

3) Extract the interested line using the following Regular Expression "swfArgs(\\s*)=(\\s*)\\{(.*)\\}"

var ytPattern = "swfArgs(\\s*)=(\\s*)\\{(.*)\\}";
var re = new RegExp(ytPattern);
var matchVar = eval('({' + re.exec(strDoc) + '})');
Now from matchVar get the values like matchVar['video_id'] or matchVar['sk']

Once you the values substitute in

Disclaimer: If Youtube changes its page this script will not work. This is working as of Sept 6 2008.