下载Facebook相册的脚本

时间:2019-06-26 14:53:35

标签: javascript html

我正在尝试通过编写可运行的Facebook相册下载器来了解JavaScript。例如,我希望它下载此相册中的所有照片:https://www.facebook.com/pg/FacebookUK/photos/?tab=album&album_id=473083416653&ref=page_internal

除了<a>标签的rel = theater属性似乎搞乱了我所依赖的单击下载功能之外,我的代码几乎可以正常工作。我尝试删除此属性,但似乎无法成功删除。这是我的脚本的样子:

var album = document.getElementsByClassName("_2eea");
var n = album.length;
for (var i = 0; i < n; i++) {
    var image = album[i];
    image = image.children[0];
    image.setAttribute('download', i.toString().concat(".jpg") );
    image.setAttribute('href', image.children[0].getAttribute("src") )
    image.click();
}

“点击”后,剧院的显示屏打开,然后挂起。我不知道该如何抑制。另外,如果有更好的策略来编码此下载器,请告诉我!

1 个答案:

答案 0 :(得分:1)

您可以使用Fetch API将每个图像作为斑点。然后,您可以使用window.URL.createObjectURL创建代表给定对象的URL。然后,将此URL添加到标记中并添加下载属性。

function getBlob(url) {
    return fetch(url).then(function(response) { return response.blob(); })
}

const album = document.getElementsByClassName("_2eea");
const n = album.length;
for (let i = 0; i < n; i++) {
    const image = album[i].children[0].children[0];
    getBlob(image.src).then(function(blob) {
        const a = document.createElement("a");
        document.body.appendChild(a);
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = i + "." + blob.type.slice(6);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
    });
}