Reputation: 3153
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?
Upvotes: 8
Views: 68654
Reputation: 835
Here's how to use it with the Fetch API using a Promise:
export async function download(url) {
return new Promise((res, rej) => {
fetch(url).then(res => res.blob()).then(file => {
const tempUrl = URL.createObjectURL(file);
const aTag = document.createElement("a");
aTag.href = tempUrl;
aTag.download = url.replace(/^.*[\\\/]/, '');
document.body.appendChild(aTag);
aTag.click();
URL.revokeObjectURL(tempUrl);
aTag.remove();
res();
}).catch(err => {
rej(err);
});
});
}
Source: https://www.codingnepalweb.com/download-file-from-url-with-javascript/
Upvotes: 1
Reputation: 135
<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
Upvotes: 3
Reputation: 3853
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.
Upvotes: 3