Skip to content

Instantly share code, notes, and snippets.

@sahilatahar
Created June 15, 2024 09:52
Show Gist options
  • Save sahilatahar/b76c485be896b50a99c4112ac9973a4a to your computer and use it in GitHub Desktop.
Save sahilatahar/b76c485be896b50a99c4112ac9973a4a to your computer and use it in GitHub Desktop.
This JavaScript script extracts URLs of images from the current webpage and copies them to the clipboard when run in the browser console (F12). It filters URLs by common image file extensions and handles potential lazy loading scenarios, ensuring extracted URLs are unique before copying.
// This script fetches all image URLs from the current webpage and copies them to the clipboard.
// To use, open the webpage, open the browser console (F12), paste this script, and run it.
// Ensure you allow clipboard access when prompted by the browser.
// The script can be customized to filter URLs based on common image extensions or other criteria.
// It can also be adjusted to extract URLs from <img> tags with lazy loading.
// Function to filter URLs based on common image extensions
const filterURLs = (urls) => {
const keywords = [".jpg", ".jpeg", ".png", ".gif", ".webp"]
let filteredURLs = urls.filter((url) =>
keywords.some((keyword) => url.includes(keyword))
)
// To exclude URLs containing specific keywords, use the following code:
// const excludedKeywords = ["avatar", "logo"]
// filteredURLs = urls.filter((url) => {
// return !excludedKeywords.some((keyword) => url.includes(keyword))
// })
return filteredURLs
}
// Function to extract image URLs from <img> tags on the webpage
const fetchImagesURL = () => {
const imgElements = document.querySelectorAll("img")
let urls = []
imgElements.forEach((img) => {
urls.push(img.src)
// Comment out the above line and uncomment the below line
// if images have lazy loading and image URLs are stored in 'data-src' attribute
// urls.push(img.getAttribute("data-src"));
})
// Remove duplicate URLs
urls = [...new Set(urls)]
// Uncomment the below line to filter the URLs and customize the filterURLs function as needed
// urls = filterURLs(urls);
// Uncomment the below line to log the URLs to the console
// console.log(urls);
// Copy URLs to the clipboard
navigator.clipboard.writeText(urls.join("\n"))
alert("Image URLs copied to clipboard.")
console.log("Image URLs copied to clipboard.")
}
// Wait for 3 seconds to ensure the user can focus on the webpage document,
// otherwise, a 'document not focused' error may occur and the clipboard won't copy the URLs.
setTimeout(() => {
fetchImagesURL()
}, 3000)
console.log("Now click on the webpage to focus on the document...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment