特定のページの画像を一括DLする
manifest.json
jsファイルでdocument.querySelectorを使う場合は
service_workerやpopup.jsではなく、content_scriptsを使わないとエラーになるので注意
(※default_iconはブラウザの右上に出るアイコンを指す)
(※run_atでドキュメントの読み込みが完了してからjsファイルを実行する)
{
"manifest_version": 3,
"version": "1.0",
"name": "image downloader",
"description": "そのページのIMGを一括ダウンロード",
"icons": {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content-scripts.js"],
"run_at": "document_end"
}
],
"action": {
"default_icon": "icon.png"
}
}
content-scripts.js
// 関数内でawaitを使いたいので、非同期(Asynchronous)関数として定義する
// async function xxx(){}のように定義してもいいが今回はアロー関数で定義しとく
const downloadImage = async (imageSrc) => {
// 画像データをフェッチする
// フェッチが終わるまで次行のコードが実行されないようにawaitする
const img = await fetch(imageSrc);
// 画像データをblobというバイナリデータとして取得する
// blob = Binary Large Object
// バイナリデータ = 0と1で構成されるコンピュータしか読めないデータ
const blob = await img.blob();
// オブジェクトURLを生成する
const imgURL = URL.createObjectURL(blob);
// バイナリデータオブジェクトからmimeTypeを取得する
// マイムタイプとはファイルの種類を表す情報のことで
// 「text/html」「text/plain」などがmimeTypeに該当する
// 上記はそれぞれ「.txt」「.html」という拡張子が対応している
const mimeTypeArray = blob.type.split('/');
// mimeTypeから拡張子を取得する
const extension = mimeTypeArray[1];
// aタグをつくり、クリックしたらimgURLに飛ばせるようにする
const a = document.createElement('a');
a.href = imgURL;
// imgURLに行くとダウンロードできるファイル名を決める
a.download = `filename.${extension}`;
// bodyタグ内にaタグを入れてクリックする
document.body.appendChild(a);
a.click();
// 念のためaタグを消す
document.body.removeChild(a);
}
const sleep = (time) => new Promise((r) => setTimeout(r, time));
// ページの読み込みが完了してから関数を実行する
window.onload = async function() {
for (const image of document.querySelectorAll('img')) {
// sleepしないと画像をすべてダウンロードできない
await sleep(1000);
downloadImage(image.src)
.then( () => {
console.log('ダウンロード完了');
})
.catch( (error) => {
console.log('Download failed. ${error}');
});
}
}