Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download video with JavaScript

I am working on video downloader extension for Google Chrome, and it is my first project (I am making Chrome extension for the first time). As I know you should use JavaScript for functionality of extension.

I want to do following: I am on some website where is some video player and i want to let user to download that video. I think Video Downloader Plus is related to my purpose. So how can I let user do functional above?

like image 906
iLiA Avatar asked Sep 19 '19 11:09

iLiA


2 Answers

Use JavaScript to look through the user's DOM.

Take anything that's <embed> on the page...

document.getElementsByTagName("embed")

That's usually a video player. The embed tag has a URL, use JavaScript to parse the URL that's written in the embed tag, you have your video URL. if you use JavaScript to navigate to a page, you can effectively download it.

For instance if you used

window.location.href = 'VIDEO URL'; 

you would download the video. Example embedded code:

   <embed width="420" height="315"
    src="https://www.youtube.com/embed/tgbNymZ7vqY">

Please note: usually people are using iframes now to plop a video onto the page:

<iframe width="420" height="315"
src="https://www.youtube.com/embed/tgbNymZ7vqY">
</iframe>

So maybe your code should be able to parse things like YouTube URLs within iframes, as well as embedded videos.

like image 153
Max Alexander Hanna Avatar answered Oct 16 '22 13:10

Max Alexander Hanna


<button onclick="downloadImage()">Download Image</button>
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();
}

If you see cors problem then adds It will works only download with image and video

like image 2
Mohaimen Khalid Avatar answered Oct 16 '22 12:10

Mohaimen Khalid