JavaScriptでページ上の画像をダウンロードする方法

コード


const downloadImage = async (imageSrc) => {
    try {
        // fetchで画像データを取得
        const image = await fetch(imageSrc);
        const imageBlob = await image.blob();
        const imageURL = URL.createObjectURL(imageBlob);

        // 拡張子取得
        const mimeTypeArray = imageBlob.type.split('/');
        const extension = mimeTypeArray[1];

        // ダウンロード
        const link = document.createElement('a');
        link.href = imageURL;
        link.download = `fileName.${extension}`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    } catch (error) {
        throw new Error(`${error}. Image src: ${imageSrc}`);
    }
}

// img要素を全て取得してループ、srcの値をdownloadImage関数に渡してダウンロード
for (const image of document.querySelectorAll('img')) {
    downloadImage(image.src)
        .then(() => {
            console.log('Download complete');
        })
        .catch((error) => {
            console.log(`Download failed. ${error}`);
        });
}

参考