El siguiente script busca la url de '<img src=' para descargarla ¿Cómo seria para que descarge la url pero de '<a href=' ?
<a href="https:// ... /MMG2.jpg"><img src="https:// .../38060.jpg"></img></a>
function saveImage(e, img=e.target){
let {src, name} = img,
a = document.createElement("a");
ext = src.replace(/.*(\.[a-z]{3,4})$/i, '$1');
name = (name == null || name =='') ? src.replace(/.*\//i, '') : name.toLowerCase().replace(/\s/g, '_') + ext;
a.style = "display: none";
fetch(src)
.then(response => response.blob())
.then(blob=> {
console.log(blob);
var blobUrl = window.URL.createObjectURL(blob);
a.href = blobUrl;
a.download = name;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(blobUrl);
a.remove();
})
.then(()=>img.className="downloaded");
}
window.addEventListener('load', ()=> {
let allImages = document.querySelectorAll('img');
allImages.forEach(img => {
img.classList.add('save-image-on-click');
img.insertAdjacentHTML('afterEnd', `<span class="image-download-indicator" style="--src:url(${img.src})"></span>`);
img.addEventListener('click', saveImage)
});
});
Para descargar la URL de `<a href>` en lugar de `<img src>` en el script presentado, simplemente debes seleccionar los elementos `<a>` en lugar de los elementos `<img>` y obtener la URL de la imagen a través del atributo `href` en lugar del atributo `src`. Aquí te dejo una posible solución:
```
function saveImage(e, link=e.target) {
let {href, name} = link,
a = document.createElement("a");
ext = href.replace(/.*(\.[a-z]{3,4})$/i, '$1');
name = (name == null || name =='') ? href.replace(/.*\//i, '') : name.toLowerCase().replace(/\s/g, '_') + ext;
a.style = "display: none";
fetch(href)
.then(response => response.blob())
.then(blob=> {
console.log(blob);
var blobUrl = window.URL.createObjectURL(blob);
a.href = blobUrl;
a.download = name;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(blobUrl);
a.remove();
})
.then(()=>link.className="downloaded");
}
window.addEventListener('load', ()=> {
let allLinks = document.querySelectorAll('a');
allLinks.forEach(link => {
let img = link.querySelector('img');
if (img != null) {
link.classList.add('save-image-on-click');
link.insertAdjacentHTML('afterEnd', `<span class="image-download-indicator" style="--src:url(${img.src})"></span>`);
link.addEventListener('click', (e) => {
saveImage(e, link);
});
}
});
});
```
En este caso, se seleccionan todos los elementos `<a>` en lugar de `<img>` y, para cada uno de ellos, se busca si contiene un elemento `<img>` dentro de él. Si es así, se añade la clase y se añade el evento de guardar la imagen. Cuando se llama a `saveImage`, se pasa el elemento `<