Click here to Skip to main content
14,695,085 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am making a chrome extension so you can download images when clicking on them. The problem is that it is a bit buggy, so any help would be awesome. Here is the javascript:

var myImg = document.querySelector('img');
myImg.addEventListener("click", () => {
var a = document.createElement('a');
a.href = myImg.src;
a.download = myImg.src;
document.body.appendChild(a);
a.click();
});

The problem is it doesnt allways work on websites, and it only works if there is one image, how can I change this? Is there a way to make it so it only downloads the image you click on and not all of them?

What I have tried:

I would assume that maybe you should add an id to the image that the user clicks on, then download the value of the id. But I am not sure how to do that. Thank you so much for any help you might give. Have a good day!
Posted
Updated 29-Aug-20 4:58am

The reason it works for one and not all, above code has to be applied for all the elements.
You use: query selector
The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.


You need to find all img tags and add click handler to all:
// Pure JS:
document.addEventListener('DOMContentLoaded', function() {
    
    var imgElements = document.body.getElementsByTagName("img");  // gets all the iamges of webpage
    Array.prototype.forEach.call( imgElements, function ( el ) {  // loops through all the images
        el.addEventListener("click", () => {.                     // attaches click handler one by one
            var a = document.createElement('a');
            a.href = el.src;
            a.download = el.src;
            document.body.appendChild(a);
            a.click();
       });
    }

Take cue from here: How to Build a Chrome Extension | Chapter 6: How to replace images on a website with your own images | Heptagon[^]

PS: Above code is more from my memory and might need some change. Intent is to share what could be done and where is the gap. Try out.
   

$(document).ready(function () {
$("img").click(function () {
var t = document.createElement('a');
t.href = this.src;
t.download = this.src;
document.body.appendChild(t);
t.click();
document.body.removeChild(t);
});
});




please try this code.
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900