make me a javascript code to automatically download an image in a website. the link will…
- User
make me a javascript code to automatically download an image in a website. the link will be contained in an element as such:
" "
the target image being downloaded begins with "https://static.wikia.nocookie.net/leagueoflegends/images/" and ends with .jpg, ignoring the "/revision/latest/scale-to-width-down/1000?cb=20200917183858" part
- Assistant
Here's a JavaScript code snippet that automatically downloads the image from the provided link:
// Find the <div> element with class "media" const divElement = document.querySelector('div.media'); // Find the <img> element within the <div> element const imgElement = divElement.querySelector('img'); // Get the source attribute of the <img> element const src = imgElement.getAttribute('src'); // Extract the URL part between "https://static.wikia.nocookie.net/leagueoflegends/images/" and ".jpg" const startIndex = src.indexOf("https://static.wikia.nocookie.net/leagueoflegends/images/") + "https://static.wikia.nocookie.net/leagueoflegends/images/".length; const endIndex = src.indexOf(".jpg") + ".jpg".length - startIndex; const imageUrl = src.substr(startIndex, endIndex); // Create a new <a> element to initiate the download const downloadLink = document.createElement('a'); downloadLink.href = imageUrl; downloadLink.download = 'image.jpg'; // Append the <a> element to the document body and trigger the click event to start the download document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink);This code retrieves the image URL from the provided HTML code by finding the element with class "media" and then extracting the source attribute of the element within it. It extracts the URL part between the desired start and end indices. Then, it creates a new element with the extracted URL as the download link, sets the download attribute to "image.jpg", appends the element to the document body, triggers a click event on the element to start the download, and finally removes the element from the document body.
Please note that the download may be blocked by browser settings or popup blockers depending on the user's configuration.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.