Spa image downloader

// 
// This works for SPA's which load images dynamically.
// put the script in the devtools, and load images. You will see a number increase when new images load. 
// When the number stops increasing you can press the button in the bottom right.
// then you can press ctrl+s in order to get all of the images you've downloaded.
//

{
	// 1. grab all of the current images, and put the src into the array.
	let imgs = $$('img').map(img=>img.src)

	// 2. add a mutationObserver too the body.
	const observer = new MutationObserver(function(mutationList, observer) {
		for(const mutationItem of mutationList) {
			if(mutationItem.target.matches('img')) {
				checkImg(mutationItem.target)
			}
			const subImgs = $$('img', mutationItem.target)
			subImgs.forEach(checkImg)
		}
	})
	observer.observe(
		document.body, 
		{
			attributes: true,
			childList: true,
			subtree: true
		}
	)

	// 3. add a button, to put all of the images in the DOM, when pressed.
	{
		var btnEl = document.createElement('button')
		addStyles(btnEl,{
			position:'fixed',
			right: '1rem',
			bottom: '1rem',
			padding: '1rem',
			background: 'black',
			color: 'white'
		})
		btnEl.textContent = 'Add Them'
		btnEl.onclick = addThem
		document.body.appendChild(btnEl)
	}


	// 4. define helper functions

	// function to check a single image
	function checkImg(imgNode) {
		if(!imgs.includes(imgNode.src)) {
			imgs.push(imgNode.src)
			console.log(imgs.length)
		}
	}

	// function to add all of the images
	function addThem() {
		let el = $$('#img-download-thing-s34F4x')[0]
		if(el == undefined) {
			el = document.createElement('div')
			el.id = 'img-download-thing'
			document.body.appendChild(el)
		}
		
		empty(el)
		
		for(const imgSrc of imgs) {
			const imgEl = document.createElement('img')
			imgEl.src = imgSrc
			el.appendChild(imgEl)
		}
	}

	// 5. define generic DOM helper functions
	function addStyles(el, styleObj) {
		for(let k in styleObj) {
			el.style[k] = styleObj[k]
		}
	}

	function $$(selector, rootNode=document) {
		return Array.from(rootNode.querySelectorAll(selector))
	}

	function empty(el) {
		let fc = el.firstChild
		while(fc) {
			el.removeChild(fc)
			fc = el.firstChild
		}
	}
}