Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I download a video given its URL in JavaScript?

I have a URL, for example this:

https://r6---sn-vgqsrn76.googlevideo.com/videoplayback?expire=1566535969&ei=wRxfXezPAoORV-3ogpgK&ip=185.27.134.50&id=o-ALFdSvuvmX_bqDsm4oRW7q9c4igbKlBmECWdISuA4Jxe&itag=22&source=youtube&requiressl=yes&mime=video%2Fmp4&ratebypass=yes&dur=624.175&lmt=1529213992430932&fvip=6&c=WEB&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cmime%2Cratebypass%2Cdur%2Clmt&sig=ALgxI2wwRAIgZzTTsBPpVznwCvzArBFuSF7Bm3yhcO0rwQdfOjBibnsCIBqf8iHuAwahqi0T6qZ3MNbj8BfLgGo2Y3fPOi96RgEV&redirect_counter=1&cm2rm=sn-aigeey7d&req_id=8f890b1c72fda3ee&cms_redirect=yes&mip=2607:fea8:4d9f:fa68:40a2:35d0:8863:2d17&mm=34&mn=sn-vgqsrn76&ms=ltu&mt=1566514280&mv=m&mvi=5&pl=41&lsparams=mip,mm,mn,ms,mv,mvi,pl&lsig=AHylml4wRQIgSCcxaGd_IpVykCuglJtHwewUuZZIyKKr1FBbNP5MvqsCIQCYQEUoM9SpfpySHA_13lB6SvevIuMvhyFDEcrsX0y0ig==

How can I download the video in this URL programmatically through JavaScript? I cannot use PHP, Apache, JQuery etc, only Pure JavaScript and HTML.

I have tried using download.js, but I do not think that is the right approach to download videos. I have also looked/tried at various other websites and Stack Overflow answers, but none of them fixed this issue.

EDIT: The other SO answer that someone suggested will not work since the video is on a different baseurl than my own, which means that

<a href="file" download="filename"> 

will not work on Chrome. Doing this just opens the video.

like image 487
Vishnu S. Avatar asked Nov 16 '22 02:11

Vishnu S.


1 Answers

function downloadImage() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://via.placeholder.com/150', true);
  xhr.responseType = 'blob';
  xhr.onload = function () {
    var urlCreator = window.URL || window.webkitURL;
    var imageUrl = urlCreator.createObjectURL(this.response);
    var tag = document.createElement('a');
    tag.href = imageUrl;
    tag.target = '_blank';
    tag.download = 'sample.png';
    document.body.appendChild(tag);
    tag.click();
    document.body.removeChild(tag);
  };
  xhr.onerror = err => {
    alert('Failed to download picture');
  };
  xhr.send();
}
like image 181
ixhimanshu Avatar answered Mar 12 '23 17:03

ixhimanshu