Friday, May 1, 2020

Script to Download Facebook Videos

How to download a video from sites is a recurrent question of every users. In this article it is described a simple method which allows download either private and public videos from Facebook just by adding a bookmark with some javascript to your browser.

A 'bookmarklet' is a bookmark stored in a web browser that contains JavaScript commands that add new features to the browser. The way to add a bookmarklet is as simple as write a JavaScript function, and call it with the `javascript:` URL protocol
javascript:(function(){alert('a')})()

But first we need to encode the function
javascript:(function()%7Balert('a')%7D)()

In our case, to download a Facebook video the function needed is:
(function(){
  fetch(location.pathname, {method: 'GET'})
    .then((r) => r.text())
    .then(html => new DOMParser().parseFromString(html, 'text/html'))
    .then(d => window.open(d.head.querySelectorAll('meta[property="og:video"]')[0].content, '_blank'))
})();

Thus, the fragment that should be copied and pasted the the bookmark is:
javascript:%28function%28%29%7Bfetch%28location.pathname%2C%20%7Bmethod%3A%20%27GET%27%7D%29.then%28%28r%29%20%3D>%20r.text%28%29%29.then%28html%20%3D>%20new%20DOMParser%28%29.parseFromString%28html%2C%20%27text%2Fhtml%27%29%29.then%28d%20%3D>%20window.open%28d.head.querySelectorAll%28%27meta%5Bproperty%3D"og%3Avideo"%5D%27%29%5B0%5D.content%2C%20%27_blank%27%29%29%3B%7D%29%28%29%3B%0A

The following video shows how to add the bookmarklet to Chrome, and how to use it.