// ==UserScript==
// @name 以图搜图
// @name:zh-CN 以图搜图
// @name:en Image Search — Reverse Image Search from Any Image
// @namespace https://github.com/yilecoding/helper-scripts
// @version 2025.11.07.11
// @description 在网页图片上按住 Alt 点右键(或鼠标悬停按 S),弹出搜图菜单,一键用 Google Lens / Bing / Yandex / 百度识图 / SauceNAO / TinEye / IQDB / ascii2d / Trace.moe 搜这张图;本地、内网、canvas 图片自动改为上传。
// @description:zh-CN 在网页图片上按住 Alt 点右键(或鼠标悬停按 S),弹出搜图菜单,一键用 Google Lens / Bing / Yandex / 百度识图 / SauceNAO / TinEye / IQDB / ascii2d / Trace.moe 搜这张图;本地、内网、canvas 图片自动改为上传。
// @description:en Alt + right-click any image (or hover it and press S) to pop up a reverse image search menu: Google Lens / Bing / Yandex / Baidu / SauceNAO / TinEye / IQDB / ascii2d / Trace.moe. Local, intranet and canvas images are uploaded instead.
// @author 壹樂(V:ita1125)
// @match *://*/*
// @grant GM_openInTab
// @grant GM_setClipboard
// @grant GM_download
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_xmlhttpRequest
// @grant GM_listValues
// @grant GM_deleteValue
// @connect lens.google.com
// @connect *
// @license MIT
// @run-at document-end
// @noframes
// @homepageURL https://github.com/yile2020/helper-scripts
// @supportURL https://github.com/yile2020/helper-scripts/issues
// @updateURL https://raw.githubusercontent.com/yile2020/helper-scripts/main/image-search/image-search.user.js
// @downloadURL https://raw.githubusercontent.com/yile2020/helper-scripts/main/image-search/image-search.user.js
// ==/UserScript==
// 脚本持续更新维护,欢迎 star / watch 仓库获取最新版本:
// https://github.com/yile2020/helper-scripts
(function () {
'use strict';
/** 统一日志前缀,控制台过滤「以图搜图」即可只看本脚本的输出。 */
const TAG = '[以图搜图]';
// =========================================================================
// 配置
// =========================================================================
const CONFIG = {
zIndex: 2147483647,
menuMargin: 8, // 菜单离视口边缘至少留这么多像素,贴边时翻到鼠标另一侧
/*
* 鼠标悬停在图片上时按这个键(不带修饰键)弹出菜单。设成 '' 关闭。
* 输入框、可编辑区域里不响应;鼠标下面不是图片时按键原样交给页面。
*/
hoverKey: 's',
/*
* 懒加载库把真图地址藏在这些属性里,src 只是占位图(常见是 1×1 的 data: gif)。
* 按顺序取第一个有值的。
*/
lazyAttrs: [
'data-src', 'data-original', 'data-lazy-src', 'data-lazy', 'data-actualsrc',
'data-original-src', 'data-echo', 'lazy-src',
],
lazySrcsetAttrs: ['data-srcset', 'data-lazy-srcset'],
fetchTimeout: 30000, // 取图片字节的超时(毫秒)
uploadTimeout: 60000, // 上传到引擎的超时
maxUploadBytes: 20 * 1024 * 1024, // 超过就不传了(各家的上限都没有核实过,取个宽松值)
};
const enc = encodeURIComponent;
/*
* 引擎表。
* url(imageUrl) 「按地址搜」的结果页地址
* upload(blob) 「上传图片搜」,返回 Promise<结果页地址>
* relay 「接力上传」:结果页是 POST 表单直接返回的 HTML、或者要页面脚本签名的引擎,
* 在原页面拿不到结果地址。把图片暂存进 GM 存储,打开引擎自己的页面(landing),
* 由本脚本在那个页面里 run(file) 把图交给它的表单 —— 见「接力上传」一节
* noUpload 两种上传都没有时写明原因,上传模式下菜单里置灰并显示这句话
* 各地址格式、上传接口的核实情况见 notes.md —— 有几家只能从公开资料确认,本机网络到不了。
* defaultOn: false 的默认不出现在菜单里(能打开但实测搜不出结果的)。
*/
const ENGINES = [
{ id: 'lens', name: 'Google Lens', defaultOn: true,
url: u => 'https://lens.google.com/uploadbyurl?url=' + enc(u),
upload: blob => uploadToLens(blob) },
{ id: 'bing', name: 'Bing', defaultOn: true,
url: u => 'https://www.bing.com/images/search?view=detailv2&iss=sbi&q=imgurl:' + enc(u),
noUpload: 'Bing 的上传接口没有核实,暂不支持' },
{ id: 'yandex', name: 'Yandex', defaultOn: true,
url: u => 'https://yandex.com/images/search?rpt=imageview&url=' + enc(u),
noUpload: 'Yandex 的上传接口实测只返回「服务建设中」,暂不支持' },
{ id: 'baidu', name: '百度识图', defaultOn: true,
url: u => 'https://graph.baidu.com/pcpage/index?tpl_from=pc&queryImageUrl=' + enc(u),
// 上传接口要页面脚本现算的 sdkParams 签名,自己拼请求会被拒(实测 status 1002 / Reject);
// 按地址搜也一样,只认页面输入框 —— 两条路都由本脚本在识图页里代填
relay: { landing: 'https://graph.baidu.com/pcpage/index?tpl_from=pc', run: file => baiduRelayFile(file) } },
{ id: 'sogou', name: '搜狗识图', defaultOn: false,
url: u => 'https://pic.sogou.com/ris?flag=1&drag=0&query=' + enc(u),
noUpload: '搜狗识图没有找到能用的上传入口' },
{ id: 'saucenao', name: 'SauceNAO', defaultOn: true,
url: u => 'https://saucenao.com/search.php?url=' + enc(u),
relay: { landing: 'https://saucenao.com/', run: file => submitForm('/search.php', [{ name: 'file', file }]) } },
{ id: 'tineye', name: 'TinEye', defaultOn: true,
url: u => 'https://tineye.com/search?url=' + enc(u),
noUpload: 'TinEye 的上传接口没有核实,暂不支持' },
{ id: 'iqdb', name: 'IQDB', defaultOn: true,
url: u => 'https://iqdb.org/?url=' + enc(u),
relay: {
landing: 'https://iqdb.org/',
run: file => submitForm('/', [{ name: 'MAX_FILE_SIZE', value: '8388608' }, { name: 'file', file }]),
} },
{ id: 'ascii2d', name: 'ascii2d', defaultOn: true,
url: u => 'https://ascii2d.net/search/url/' + enc(u),
noUpload: 'ascii2d 的上传要 CSRF 令牌,还套着 Cloudflare 人机验证' },
{ id: 'tracemoe', name: 'Trace.moe(动画截图)', defaultOn: true,
url: u => 'https://trace.moe/?url=' + enc(u),
noUpload: 'trace.moe 的上传方式没有核实,暂不支持' },
];
const canUpload = e => !!(e.upload || e.relay);
const HOST_ID = '__image-search-host';
const HOST = location.hostname;
// =========================================================================
// 设置(GM 存储)
// =========================================================================
/*
* 存的是 { enabled: 启用的引擎 id(按菜单顺序), known: 保存时脚本认识的全部 id }。
* known 用来区分「用户关掉的」和「脚本更新后新加的」:新引擎不在 known 里,
* 按它的 defaultOn 追加到末尾;否则用户一保存过设置,以后加的引擎就永远不会出现。
*/
const Settings = {
enabledEngines() {
const saved = GM_getValue('engines', null);
if (!saved || !Array.isArray(saved.enabled)) return ENGINES.filter(e => e.defaultOn);
const byId = new Map(ENGINES.map(e => [e.id, e]));
const known = new Set(saved.known || []);
const list = saved.enabled.map(id => byId.get(id)).filter(Boolean);
for (const e of ENGINES) if (e.defaultOn && !known.has(e.id) && !list.includes(e)) list.push(e);
return list;
},
saveEngines(ids) {
GM_setValue('engines', { enabled: ids, known: ENGINES.map(e => e.id) });
},
resetEngines() {
GM_setValue('engines', null);
},
siteDisabled() {
return (GM_getValue('disabledHosts', []) || []).includes(HOST);
},
setSiteDisabled(off) {
const list = (GM_getValue('disabledHosts', []) || []).filter(h => h !== HOST);
if (off) list.push(HOST);
GM_setValue('disabledHosts', list);
},
};
/**
* 把 prompt 里填的内容解析成引擎 id 列表:逗号 / 空格 / 顿号分隔,填 id 或序号都行。
* 返回 { ids } 或 { error }。
*/
function parseEngineInput(text) {
const tokens = String(text).split(/[\s,,、;;]+/).filter(Boolean);
const ids = [];
for (const tok of tokens) {
const n = /^\d+$/.test(tok) ? +tok : NaN;
const engine = n ? ENGINES[n - 1] : ENGINES.find(e => e.id === tok.toLowerCase());
if (!engine) return { error: `不认识「${tok}」` };
if (!ids.includes(engine.id)) ids.push(engine.id);
}
if (!ids.length) return { error: '至少要启用一个引擎' };
return { ids };
}
// =========================================================================
// 取图片地址
// =========================================================================
/**
* 转成绝对地址。#hash 去掉:服务器根本收不到它,带着反而会被搜图引擎当成地址的一部分。
*/
function normalizeUrl(raw) {
if (!raw) return null;
raw = raw.trim();
if (!raw) return null;
try {
const u = new URL(raw, document.baseURI);
if (!/^(https?|data|blob):$/.test(u.protocol)) return null;
if (u.protocol !== 'data:') u.hash = '';
return u.href;
} catch (e) {
return null;
}
}
/**
* 解析 srcset,返回 [{ url, w, x }]。没有描述符的候选按 1x 算。
*
* 不能按「逗号 + 空白」切:压缩过的 HTML 里逗号后面常常没有空格(a.jpg 1x,b.jpg 2x)。
* 也不能按逗号切:Cloudinary 之类的 URL 自带逗号(c_fill,w_800)。按规范来 ——
* URL 是一段不含空白的字符,URL 末尾的逗号才是分隔符;描述符读到下一个逗号为止。
*/
function parseSrcset(srcset) {
const out = [];
const s = srcset || '';
let i = 0;
while (i < s.length) {
while (i < s.length && /[\s,]/.test(s[i])) i++;
if (i >= s.length) break;
let start = i;
while (i < s.length && !/\s/.test(s[i])) i++;
let url = s.slice(start, i);
let desc = '';
if (url.endsWith(',')) {
url = url.replace(/,+$/, '');
} else {
start = i;
while (i < s.length && s[i] !== ',') i++;
desc = s.slice(start, i).trim();
}
if (!url) continue;
const m = /^([\d.]+)([wx])$/i.exec(desc);
out.push({
url,
w: m && m[2].toLowerCase() === 'w' ? parseFloat(m[1]) : 0,
x: m && m[2].toLowerCase() === 'x' ? parseFloat(m[1]) : 1,
});
}
return out;
}
/** 几个 srcset 合起来挑最大的。w 描述符一律压过 x(有宽度的才是真实尺寸)。 */
function bestFromSrcsets(srcsets) {
let best = null;
let bestScore = -1;
for (const s of srcsets) {
for (const c of parseSrcset(s)) {
const score = c.w ? 1e6 + c.w : c.x;
if (score > bestScore) {
best = c.url;
bestScore = score;
}
}
}
return best;
}
/**
* 一个
取一张: + srcset 里最大的 > 懒加载属性 > currentSrc > src。
* currentSrc 是浏览器按屏幕挑的那一张,往往不是最大的,所以排在 srcset 后面。
* 懒加载属性里的 data: 是占位图,跳过;src 本身是占位图时同理要先看懒加载属性。
*/
function pickImgUrl(img) {
const srcsets = [];
const pic = img.parentElement;
if (pic && pic.tagName === 'PICTURE') {
for (const s of pic.children) {
if (s.tagName !== 'SOURCE') continue;
for (const a of ['srcset', ...CONFIG.lazySrcsetAttrs]) srcsets.push(s.getAttribute(a));
}
}
for (const a of ['srcset', ...CONFIG.lazySrcsetAttrs]) srcsets.push(img.getAttribute(a));
const best = bestFromSrcsets(srcsets);
if (best) return best;
for (const a of CONFIG.lazyAttrs) {
const v = img.getAttribute(a);
if (v && !v.trim().startsWith('data:')) return v;
}
return img.currentSrc || img.getAttribute('src');
}
/** background-image 计算值里的第一个 url(...);渐变之类的忽略。 */
function backgroundUrl(el) {
const value = getComputedStyle(el).backgroundImage;
if (!value || value === 'none') return null;
const m = /url\(\s*(['"]?)(.*?)\1\s*\)/.exec(value);
return m ? m[2] : null;
}
/**
* 搜图网站从公网拿不到的地址,返回原因;拿得到返回 null。
* 只能按地址判断:要登录 cookie 才能看的图从地址上看不出来,菜单里留了手动「改用上传」。
*/
function privateReason(url) {
if (url.startsWith('data:')) return '内嵌的 data: 图片';
if (url.startsWith('blob:')) return '页面生成的 blob: 图片';
let host;
try {
host = new URL(url).hostname.toLowerCase();
} catch (e) {
return '地址无法解析';
}
if (host.startsWith('[')) {
// IPv6:回环、唯一本地 fc00::/7、链路本地 fe80::/10
return /^\[(::1?|f[cd][0-9a-f]{0,2}:.*|fe[89ab][0-9a-f]?:.*)\]$/.test(host) ? '内网地址' : null;
}
const ip = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(host);
if (ip) {
const [a, b] = [+ip[1], +ip[2]];
if (a === 10 || a === 127 || a === 0) return '内网地址';
if (a === 172 && b >= 16 && b <= 31) return '内网地址';
if (a === 192 && b === 168) return '内网地址';
if (a === 169 && b === 254) return '内网地址';
if (a === 100 && b >= 64 && b <= 127) return '内网地址'; // 运营商级 NAT
return null;
}
// 没有点的主机名(http://nas/、http://intranet/)只在局域网 DNS 里有
if (!host.includes('.')) return '内网地址';
if (/\.(localhost|local|lan|internal|intranet|corp|home|home\.arpa)$/.test(host)) return '内网地址';
return null;
}
/**
* canvas 转成 data: 地址。被跨域图片「污染」过的画布读不出像素,toDataURL 直接抛 SecurityError,
* 这种不能当成「没找到图」放过去 —— 用户明明点在一张图上,得告诉他为什么不行。
*/
function canvasTarget(el) {
if (!el.width || !el.height) return null;
try {
return { url: el.toDataURL('image/png'), el, kind: 'canvas', privateReason: 'canvas 画布' };
} catch (e) {
return { url: null, el, kind: 'canvas', error: '这个画布画过跨域图片,浏览器不让读取像素,没法搜' };
}
}
/**
* 透明垫片图:Flickr 在照片上盖一张拉伸成照片大小的 1×1 透明 gif(spaceball.gif),
* 它在 elementsFromPoint 的最上层,不跳过的话搜的就是那个透明像素。
* 只认「挑出来的就是正在显示的那张、而且真实尺寸不超过 2×2」—— 懒加载占位图另有 data-src,不会走到这里。
*/
function isSpacer(img, raw) {
if (!img.complete || !img.naturalWidth || img.naturalWidth > 2 || img.naturalHeight > 2) return false;
return normalizeUrl(raw) === normalizeUrl(img.currentSrc || img.getAttribute('src'));
}
/** 单个元素能给出的图片,给不出返回 null。 */
function imageFromElement(el) {
if (el.tagName === 'CANVAS') return canvasTarget(el);
let raw = null;
if (el.tagName === 'IMG') {
raw = pickImgUrl(el);
if (isSpacer(el, raw)) return null;
}
// / 的背景是整页底纹,鼠标在任何空白处都会命中它,不算
else if (el !== document.documentElement && el !== document.body) raw = backgroundUrl(el);
const url = normalizeUrl(raw);
return url ? { url, el, kind: el.tagName === 'IMG' ? 'img' : 'background', privateReason: privateReason(url) } : null;
}
/**
* 鼠标位置下的图片:{ url, el, kind, privateReason?, error? },没有返回 null。
*
* 用 elementsFromPoint 从上往下逐层找,而不是只看事件的 target:Instagram、Pinterest、
* 各种防盗图的站点都在图片上盖一层透明 div,target 永远是那层壳。
* open shadow root 要进去再找一遍 —— 从 document 上只能拿到宿主元素。
*/
function findImageAt(x, y, root = document, depth = 0) {
const stack = root.elementsFromPoint(x, y);
for (const el of stack) {
if (el.id === HOST_ID) continue;
if (el.shadowRoot && el.shadowRoot !== root && depth < 5) {
const inner = findImageAt(x, y, el.shadowRoot, depth + 1);
if (inner) return inner;
}
const found = imageFromElement(el);
if (found) return found;
}
return findByRect(stack, x, y);
}
/**
* pointer-events: none 的元素不会出现在 elementsFromPoint 里(防拖拽的站常给
加这个)。
* 兜底:在最上面几层元素里找几何上盖住鼠标的
/