RMB images interactions

Alt+click = download in the current tab; Shift > new window; control > new tab;

当前为 2022-06-12 提交的版本,查看 最新版本

// ==UserScript==
// @name         RMB images interactions
// @namespace    http://tampermonkey.net/
// @version      0.23
// @description  Alt+click = download in the current tab; Shift > new window; control > new tab;
// @author       Amasoken
// @match        http*://*/*
// @grant        GM_download
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    const isTargetImage = e => e.target.tagName === 'IMG' && e.target.src;
    const isImageOnlyPage = document.querySelector('body img') === document.body.lastChild;

    document.addEventListener("contextmenu", e => {
        const {ctrlKey, altKey, shiftKey} = e;
        if ((ctrlKey + altKey + shiftKey)) {
            let imageElement = isTargetImage(e) ? e.target : e.target.querySelector('img');
            if (imageElement) {
                e.preventDefault();
                handleImageClick(e, imageElement);
                return false;
            }
        }
    }, false);

    function handleImageClick(e, imageElement = e.target) {
        const {ctrlKey, altKey, shiftKey} = e;
        const isSingleKeyPressed = ctrlKey + altKey + shiftKey === 1;
        if (!isSingleKeyPressed) return;

        // ctrl click
        if (ctrlKey) {
            e.stopPropagation();
            if (isImageOnlyPage) {
                closeWindow()
            } else {
                openInNewTab(imageElement.src);
            }
        }

        // alt click
        if (altKey) {
            e.stopPropagation();
            saveImage(imageElement.src)
            if (isImageOnlyPage) closeWindow()
        }

        // shift click
        if (isSingleKeyPressed && shiftKey ) {
            e.stopPropagation();
            !isImageOnlyPage && newWindow(imageElement.src);
            isImageOnlyPage && closeWindow();
        }
    }

    function openInNewTab(imageUrl, shouldDownload = false) {
        const link = document.createElement('a');
        link.href = imageUrl;
        link.target = "_blank";
        link.rel ="noreferrer noopener";
        link.click();
    }

    function newWindow(imageUrl) {
        window.open(imageUrl, '_blank')
    }

    function closeWindow() {
        const closeButton = document.createElement('button');
        closeButton.onclick = () => {
            window.close();
        }

        closeButton.click();
    }

    function saveImage(url) {
        const urlSplit = url.split('/');
        let fileName = urlSplit[urlSplit.length - 1];
        fileName = fileName.split('?')[0]; // drop query params if present
        fileName = decodeURI(fileName); // handle encoded url
        if (fileName.split('.').length <= 1) {
            fileName += '.jpg';
        }

        GM_download(url, fileName)
    }
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址