ImageSnatcher

ImageSnatcher te permite descargar imágenes rápidamente pasando el cursor sobre ellas y presionando la tecla S.

// ==UserScript==
// @name         ImageSnatcher
// @name:es      ImageSnatcher
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  ImageSnatcher lets you quickly download images by hovering over them and pressing the S key.
// @description:es  ImageSnatcher te permite descargar imágenes rápidamente pasando el cursor sobre ellas y presionando la tecla S.
// @author       Adam Jensen
// @match        *://*/*
// @grant        none
// @license MIT
// ==/UserScript==

(function() {
    'use strict';

    let hoveredImage = null;

    // Listen for the mousemove event to detect the image being hovered over
    document.addEventListener('mousemove', function(event) {
        // Check if the target is an <img> tag or an element with a background image (like <a>, <div>, etc.)
        if (event.target.tagName.toLowerCase() === 'img') {
            hoveredImage = event.target;
        } else if (event.target.style.backgroundImage) {
            hoveredImage = event.target;
        } else {
            hoveredImage = null;
        }
    });

    // Listen for the keydown event to detect when the 'S' key is pressed
    document.addEventListener('keydown', function(event) {
        if (event.key.toLowerCase() === 's' && hoveredImage) {
            let imageUrl = null;
            let imageTitle = '';

            // Check if hovered element is an <img> tag
            if (hoveredImage.tagName.toLowerCase() === 'img') {
                imageUrl = hoveredImage.src;
                imageTitle = hoveredImage.alt.trim() || '';  // Use alt if available, otherwise empty string
            }
            // Check if hovered element is a background image (like <a>, <div>, etc.)
            else if (hoveredImage.style.backgroundImage) {
                // Extract the URL from the background-image property (remove quotes)
                imageUrl = hoveredImage.style.backgroundImage.replace(/url\(["']?([^"']+)["']?\)/, '$1');

                // Use the closest <a> element's href if the hovered element is an <a> with background image
                const parentAnchor = hoveredImage.closest('a');
                if (parentAnchor && parentAnchor.href) {
                    const href = parentAnchor.href;  // Get the href of the <a> element
                    // Extract the part of the URL that should be used as the filename (based on href)
                    imageTitle = href.replace(/^https?:\/\/[^\/]+/, '').replace(/[\/:*?"<>|]/g, '_'); // Clean up href to make it a valid filename
                }
            }

            // If imageTitle is empty, try to use the closest <a> href
            if (!imageTitle) {
                const parentAnchor = hoveredImage.closest('a');  // Find the closest <a> parent
                if (parentAnchor && parentAnchor.href) {
                    const href = parentAnchor.href;  // Get the href of the <a> element
                    // Extract the part of the URL that should be used as the filename (based on href)
                    imageTitle = href.replace(/^https?:\/\/[^\/]+/, '').replace(/[\/:*?"<>|]/g, '_'); // Clean up href to make it a valid filename
                }
            }

            // If imageTitle is still empty, fall back to the URL or filename from the image URL
            if (!imageTitle) {
                imageTitle = imageUrl.split('/').pop().split('?')[0]; // Use filename from URL if title is empty
            }

            // Clean the name to make it safe for file systems
            imageTitle = imageTitle.replace(/[\/:*?"<>|]/g, '_');  // Clean the name for the file

            const safeImageName = imageTitle;

            if (imageUrl) {
                // Check if the image is embedded (base64)
                if (imageUrl.startsWith('data:image/')) {
                    const a = document.createElement('a');
                    a.href = imageUrl;
                    a.download = `${safeImageName}`;
                    a.style.display = 'none';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    console.log(`Downloading embedded image: ${safeImageName}`);
                } else {

                    fetch(imageUrl)
                        .then(response => response.blob())
                        .then(blob => {
                            const a = document.createElement('a');
                            const objectURL = URL.createObjectURL(blob);
                            a.href = objectURL;
                            a.download = `${safeImageName}`;
                            a.style.display = 'none';
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a);

                            URL.revokeObjectURL(objectURL);
                            console.log(`Downloading image: ${safeImageName}`);
                        })
                        .catch(err => {
                            console.error('Error downloading the image:', err);
                        });
                }
            } else {
                console.error('Could not retrieve the image URL');
            }
        }
    });
})();