Greasy Fork

以图搜图

脚本菜单启用脚本后点击图片即可以图搜图

目前为 2023-11-25 提交的版本。查看 最新版本

// ==UserScript==
// @name         以图搜图
// @version      2.4
// @description  脚本菜单启用脚本后点击图片即可以图搜图
// @author       ChatGPT
// @match        *://*/*
// @grant        GM_registerMenuCommand
// @namespace    https://greasyfork.org/users/452911
// ==/UserScript==

(function() {
    'use strict';

    let menuBox = null;

    // 注册菜单命令
    GM_registerMenuCommand('以图搜图', function() {
        function createMenu(imageUrl) {
            if (menuBox) {
                return menuBox;
            }

            menuBox = document.createElement("div");
            menuBox.style.position = "absolute";
            menuBox.style.backgroundColor = "#fff";
            menuBox.style.border = "1px solid #ccc";
            menuBox.style.boxShadow = "0 2px 6px #aaa";
            menuBox.style.zIndex = "9999";

            let searchEngines = [
                { name: "Google", url: "https://lens.google.com/uploadbyurl?url=" },
                { name: "Yandex", url: "https://yandex.com/images/search?rpt=imageview&url=" },
                { name: "TinEye", url: "https://tineye.com/search/?url=" },
                { name: "iqdb", url: "https://iqdb.org/?url=" },
                { name: "TraceMoe", url: "https://trace.moe/?url=" },
                { name: "ascii2d", url: "https://ascii2d.net/search/url/" }
            ];

            for (let engine of searchEngines) {
                let menuItem = document.createElement("a");
                menuItem.textContent = engine.name;
                menuItem.href = engine.url + encodeURIComponent(imageUrl);
                menuItem.target = "_blank";
                menuItem.style.display = "block";
                menuItem.style.padding = "8px";
                menuItem.style.color = "#333";
                menuItem.style.textDecoration = "none";

                menuBox.appendChild(menuItem);
            }

            return menuBox;
        }

        document.addEventListener("mousedown", (event) => {
            if (event.target.tagName === "IMG") {
                event.preventDefault(); // 禁止默认行为
                let imageUrl = event.target.src;
                menuBox = createMenu(imageUrl);
                menuBox.style.top = event.pageY + "px";
                menuBox.style.left = event.pageX + "px";
                document.body.appendChild(menuBox);
            } else {
                if (menuBox && !menuBox.contains(event.target)) {
                    menuBox.remove();
                    menuBox = null;
                }
            }
        });

        document.addEventListener("mouseup", (event) => {
            if (menuBox && menuBox.contains(event.target)) {
                event.stopPropagation();
            }
        });
    });
})();