// ==UserScript==
// @name 粘贴即传图
// @namespace https://cnb.cool/IIIStudio/Code/Greasemonkey/ImgNest
// @version 0.8.21
// @description Ctrl+V 粘贴图片自动上传图床并回填链接|多图床配置|历史记录|导入导出
// @author IIIStudio
// @match *://*/*
// @run-at document-idle
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_addValueChangeListener
// @grant GM_registerMenuCommand
// @grant GM_info
// @connect p.sda1.dev
// @connect dav.jianguoyun.com
// @connect img.ink
// @connect api.imgbb.com
// @connect ibb.co
// @connect cnb.cool
// ==/UserScript==
/*
* 粘贴即传图(ImgNest)
* 作者:IIIStudio
* 仓库:https://cnb.cool/IIIStudio/Code/Greasemonkey/ImgNest
* AI 辅助开发:Deepseek-V4.1-Flash
*
* 需要连接新的图床 / WebDAV 域名时,在上面的元数据块里加一行:
* // @connect example.com
* 保存并刷新页面后生效(支持 *.example.com 通配)。
*/
(function () {
'use strict';
/* =========================================================================
* 0. 环境与通用工具
* ========================================================================= */
const VERSION = '0.8.20';
const IS_TOP = (() => {
try { return window.top === window.self; } catch (e) { return false; }
})();
const PARENT_REACHABLE = (() => {
try { return window.parent === window || !!window.parent.location.href; } catch (e) { return false; }
})();
// 同源子框架由顶层/父级实例统一接管粘贴与 UI,直接早退避免重复挂载开销
if (!IS_TOP && PARENT_REACHABLE) return;
// 向上找同源祖先的真实域名,处理 about:blank / about:srcdoc 编辑器 iframe
function resolveHost() {
try { if (location.hostname) return location.hostname; } catch (e) { /* ignore */ }
let w = window;
for (let i = 0; i < 10; i++) {
let p = null;
try { p = w.parent; } catch (e) { break; }
if (!p || p === w) break;
try {
if (p.location.hostname) return p.location.hostname;
} catch (e) { break; }
w = p;
}
try {
const ref = document.referrer;
if (ref) return new URL(ref).hostname;
} catch (e) { /* ignore */ }
return '';
}
const HOST = resolveHost();
const ZWSP = '\u200b';
const GMXHR = (typeof GM_xmlhttpRequest === 'function')
? GM_xmlhttpRequest
: (typeof GM !== 'undefined' && GM && typeof GM.xmlHttpRequest === 'function'
? (details) => GM.xmlHttpRequest(details)
: null);
const hasGMXHR = typeof GMXHR === 'function';
function gmGet(key, fallback) {
try {
if (typeof GM_getValue === 'function') {
const v = GM_getValue(key);
return v === undefined ? fallback : v;
}
} catch (e) { /* ignore */ }
try {
const raw = localStorage.getItem(key);
return raw === null ? fallback : raw;
} catch (e) { /* ignore */ }
return fallback;
}
function gmSet(key, value) {
try {
if (typeof GM_setValue === 'function') { GM_setValue(key, value); return; }
} catch (e) { /* ignore */ }
try { localStorage.setItem(key, value); } catch (e) { /* ignore */ }
}
function uuid() {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
const HTML_ESC_MAP = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
function escapeHtml(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => HTML_ESC_MAP[c]);
}
function fmtBytes(n) {
if (!n && n !== 0) return '';
if (n < 1024) return n + ' B';
if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
return (n / 1024 / 1024).toFixed(2) + ' MB';
}
function pad2(n) { return n < 10 ? '0' + n : '' + n; }
function fmtTime(ts) {
if (!ts) return '';
const d = new Date(ts);
return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()) +
' ' + pad2(d.getHours()) + ':' + pad2(d.getMinutes());
}
function debounce(fn, ms) {
let t = null;
return function (...args) {
clearTimeout(t);
t = setTimeout(() => fn.apply(null, args), ms);
};
}
function node(tag, cls, text) {
const el = document.createElement(tag);
if (cls) el.className = cls;
if (text != null) el.textContent = text;
return el;
}
async function pool(items, limit, worker) {
const queue = items.slice();
const n = Math.max(1, Math.min(limit, queue.length));
const runners = [];
for (let i = 0; i < n; i++) {
runners.push((async function run() {
while (queue.length) {
const item = queue.shift();
try { await worker(item); } catch (e) { /* worker 内部自行处理 */ }
}
})());
}
await Promise.all(runners);
}
function download(filename, content, mime) {
const blob = content instanceof Blob ? content : new Blob([content], { type: mime || 'application/json;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
(document.body || document.documentElement).appendChild(a);
a.click();
setTimeout(() => { a.remove(); URL.revokeObjectURL(url); }, 2000);
}
async function copyText(text) {
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
return true;
}
} catch (e) { /* fallthrough */ }
try {
const ta = document.createElement('textarea');
ta.value = text;
ta.style.cssText = 'position:fixed;top:-1000px;left:-1000px;opacity:0;';
document.body.appendChild(ta);
ta.select();
const ok = document.execCommand('copy');
ta.remove();
return ok;
} catch (e) {
return false;
}
}
// 只接受 http/https 绝对地址(兼容 //example.com 协议相对链接),阻断 javascript:/data: 等危险协议
function safeHttpUrl(raw) {
let s = String(raw == null ? '' : raw).trim();
if (!s) return '';
if (s.startsWith('//')) s = 'https:' + s;
try {
const u = new URL(s);
if (u.protocol === 'http:' || u.protocol === 'https:') return u.href;
} catch (e) { /* 非法 URL */ }
return '';
}
// 合并对象时跳过原型相关的键,防止导入 JSON 造成原型污染
const BLOCKED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
function safeAssign(target, ...sources) {
const out = target || {};
for (const src of sources) {
if (!src || typeof src !== 'object') continue;
for (const k of Object.keys(src)) {
if (!BLOCKED_KEYS.has(k)) out[k] = src[k];
}
}
return out;
}
/* =========================================================================
* 1. 配置
* ========================================================================= */
const CONFIG_KEY = 'piu.config';
const RECORDS_KEY = 'piu.records';
const DEFAULT_DAV_FOLDER = 'ImgNest';
const DEFAULT_DAV_FILE = 'piu-backup.json';
const PSDA1_PROVIDER = {
id: 'p-sda1',
name: '流浪图床',
enabled: true,
uploadUrl: 'https://p.sda1.dev/api/v1/upload_external_noform',
method: 'POST',
bodyType: 'binary', // binary | multipart | base64json
formField: 'file',
query: [{ key: 'filename', value: '{{filename}}' }],
fields: [],
headers: {},
withCredentials: false,
urlPath: 'data.url', // 支持 data.url / $json:data.url$ / data[0].url
urlRegex: '',
deleteUrlPath: 'data.delete_url',
maxSizeMB: 5,
timeoutMs: 30000,
retries: 1,
};
// 站点规则只有两条,白名单优先:
// 白名单 —— 用图床上传
// 黑名单 —— 不许用图床,走原生粘贴;默认 * 表示所有站点都禁止,只有白名单例外
const DEFAULT_WHITELIST = ['www.52pojie.cn', 'bbs.tampermonkey.net.cn'];
const DEFAULT_BLACKLIST = ['*'];
function defaultConfig() {
return {
schemaVersion: 4,
enabled: true,
activeProviderId: PSDA1_PROVIDER.id,
insertMode: 'url', // url | markdown | bbcode | html
historyView: 'list', // list | waterfall
autoCopy: false,
showFab: true,
shortcut: 'alt+shift+h',
providers: [JSON.parse(JSON.stringify(PSDA1_PROVIDER))],
blacklist: DEFAULT_BLACKLIST.slice(),
whitelist: DEFAULT_WHITELIST.slice(),
siteEnabled: {},
webdav: { url: '', username: '', password: '', folder: DEFAULT_DAV_FOLDER, file: DEFAULT_DAV_FILE, auto: false },
};
}
function normalizeWebdav(raw) {
return safeAssign({
url: '', username: '', password: '',
folder: DEFAULT_DAV_FOLDER, file: DEFAULT_DAV_FILE, auto: false,
}, raw || {});
}
function normalizeProvider(p) {
const base = {
id: uuid(), name: '未命名图床', enabled: true, uploadUrl: '', method: 'POST',
bodyType: 'binary', formField: 'file', query: [], fields: [], headers: {}, withCredentials: false,
urlPath: 'data.url', urlRegex: '', deleteUrlPath: 'data.delete_url',
maxSizeMB: 5, timeoutMs: 30000, retries: 1,
};
const out = safeAssign(base, p || {});
out.name = String(out.name || '').trim() || '未命名图床';
out.uploadUrl = String(out.uploadUrl || '').trim();
out.formField = String(out.formField || '').trim() || 'file';
const sizeMB = Number(out.maxSizeMB);
out.maxSizeMB = Number.isFinite(sizeMB) && sizeMB > 0 ? Math.min(sizeMB, 200) : 5;
const timeout = Number(out.timeoutMs);
out.timeoutMs = Number.isFinite(timeout) && timeout > 0 ? Math.min(Math.max(timeout, 1000), 60000) : 30000;
const retries = Number(out.retries);
out.retries = Number.isFinite(retries) ? Math.min(Math.max(Math.floor(retries), 0), 5) : 1;
if (!Array.isArray(out.query)) out.query = [];
if (!Array.isArray(out.fields)) out.fields = [];
if (!out.headers || typeof out.headers !== 'object') out.headers = {};
return out;
}
function normalizeConfig(raw) {
const cfg = safeAssign(defaultConfig(), raw || {});
if (!Array.isArray(cfg.providers) || !cfg.providers.length) cfg.providers = defaultConfig().providers;
cfg.providers = cfg.providers.map(normalizeProvider);
if (!cfg.providers.some((p) => p.id === cfg.activeProviderId)) {
cfg.activeProviderId = cfg.providers[0].id;
}
if (!Array.isArray(cfg.blacklist)) cfg.blacklist = [];
if (!Array.isArray(cfg.whitelist)) cfg.whitelist = [];
if (!cfg.siteEnabled || typeof cfg.siteEnabled !== 'object') cfg.siteEnabled = {};
if (cfg.historyView !== 'waterfall') cfg.historyView = 'list';
cfg.webdav = normalizeWebdav(cfg.webdav);
return cfg;
}
const state = {
config: null,
hostEl: null,
shadow: null,
ui: {},
list: {
cursor: null, // { createdAt, id }
hasMore: true,
loading: false,
items: [],
filters: { siteHost: '', providerId: '', q: '' },
observer: null,
},
toastSeq: 0,
};
function loadConfig() {
let raw = null;
try { raw = JSON.parse(gmGet(CONFIG_KEY, '') || 'null'); } catch (e) { raw = null; }
return normalizeConfig(raw);
}
function saveConfig() {
try {
gmSet(CONFIG_KEY, JSON.stringify(state.config));
} catch (e) {
console.warn('[粘贴即传图] 配置保存失败', e);
}
}
function activeProvider() {
const cfg = state.config;
return cfg.providers.find((p) => p.id === cfg.activeProviderId && p.enabled) ||
cfg.providers.find((p) => p.enabled) || null;
}
function siteEnabled(host) {
const v = state.config.siteEnabled[host];
return v === undefined ? true : !!v;
}
/* =========================================================================
* 2. 历史记录(脚本级存储,跨站点共享 + 解析缓存)
* ========================================================================= */
const MAX_RECORDS = 5000;
let recordsCache = { raw: null, list: [] };
function readRecords() {
const raw = gmGet(RECORDS_KEY, '[]') || '[]';
if (raw === recordsCache.raw) return recordsCache.list.slice();
let arr = [];
try {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) arr = parsed;
} catch (e) { arr = []; }
recordsCache = { raw, list: arr };
return arr.slice();
}
function writeRecords(arr) {
try {
const raw = JSON.stringify(arr);
gmSet(RECORDS_KEY, raw);
recordsCache = { raw, list: arr.slice() };
} catch (e) {
console.warn('[粘贴即传图] 历史记录写入失败', e);
}
}
function cmpDesc(a, b) {
const diff = (b.createdAt || 0) - (a.createdAt || 0);
if (diff !== 0) return diff;
const aid = String(a.id || '');
const bid = String(b.id || '');
return aid < bid ? 1 : (aid > bid ? -1 : 0);
}
function sortDesc(arr) {
arr.sort(cmpDesc);
return arr;
}
function matchFilters(r, f) {
if (f.siteHost && r.siteHost !== f.siteHost) return false;
if (f.providerId && r.providerId !== f.providerId) return false;
if (f.q) {
const q = f.q.toLowerCase();
const hay = ((r.url || '') + ' ' + (r.filename || '') + ' ' + (r.pageTitle || '')).toLowerCase();
if (!hay.includes(q)) return false;
}
return true;
}
const History = {
async add(rec) {
const arr = readRecords();
if (!rec.createdAt) {
const maxTs = arr.reduce((m, r) => Math.max(m, r.createdAt || 0), 0);
rec.createdAt = Math.max(Date.now(), maxTs + 1);
}
arr.push(rec);
sortDesc(arr);
if (arr.length > MAX_RECORDS) arr.length = MAX_RECORDS;
writeRecords(arr);
return rec;
},
// 批量合并导入(单次读写,避免导入大量记录时卡顿)
async merge(records, opts) {
const defaultMode = (opts && opts.defaultInsertedAs) || 'url';
const arr = readRecords();
const seenKey = new Set(arr.map((r) => (r.url || '') + '|' + (r.createdAt || 0)));
const seenIds = new Set(arr.map((r) => r.id));
let maxTs = arr.reduce((m, r) => Math.max(m, r.createdAt || 0), 0);
let added = 0;
let skipped = 0;
let duplicated = 0;
for (const r of records) {
const safeUrl = r && safeHttpUrl(r.url);
if (!safeUrl) { skipped++; continue; }
const createdAt = r.createdAt || (maxTs = Math.max(Date.now(), maxTs + 1));
const key = safeUrl + '|' + createdAt;
if (seenKey.has(key)) { duplicated++; continue; }
seenKey.add(key);
let id = r.id ? String(r.id) : '';
if (!id || seenIds.has(id)) id = uuid();
seenIds.add(id);
arr.push(safeAssign({
providerId: '', providerName: '', pageUrl: '', pageTitle: '',
siteHost: '', filename: '', mime: '', size: 0, insertedAs: defaultMode,
status: 'ok',
}, r, {
id,
url: safeUrl,
deleteUrl: safeHttpUrl(r.deleteUrl),
createdAt,
}));
added++;
}
if (added > 0) {
sortDesc(arr);
if (arr.length > MAX_RECORDS) arr.length = MAX_RECORDS;
writeRecords(arr);
}
return { added, skipped, duplicated };
},
async update(id, patch) {
const arr = readRecords();
const i = arr.findIndex((r) => r.id === id);
if (i === -1) return null;
arr[i] = safeAssign({}, arr[i], patch);
writeRecords(arr);
return arr[i];
},
async remove(id) {
writeRecords(readRecords().filter((r) => r.id !== id));
},
async get(id) {
return readRecords().find((r) => r.id === id) || null;
},
async list(filters, limit, cursor) {
limit = limit || 24;
return sortDesc(readRecords().filter((r) =>
matchFilters(r, filters) && (!cursor || cmpDesc(cursor, r) < 0)
)).slice(0, limit);
},
async all() {
return sortDesc(readRecords());
},
async sites() {
const map = new Map();
for (const r of readRecords()) {
const k = r.siteHost || '未知';
map.set(k, (map.get(k) || 0) + 1);
}
return Array.from(map.entries()).sort((a, b) => b[1] - a[1]);
},
async clear() {
writeRecords([]);
},
};
/* =========================================================================
* 3. 上传引擎
* ========================================================================= */
function parsePath(obj, path) {
if (obj == null || !path) return undefined;
let p = String(path).trim();
p = p.replace(/^\$json:/i, '').replace(/\$$/, '').trim();
if (!p) return undefined;
const parts = p.replace(/\[(\d+)\]/g, '.$1').split('.').filter(Boolean);
let cur = obj;
for (const key of parts) {
if (cur == null) return undefined;
cur = cur[key];
}
return cur;
}
function jsonValue(json, expr) {
if (json == null) return undefined;
let e = String(expr == null ? '' : expr).trim();
e = e.replace(/^\$json:/i, '').replace(/^\{json:/i, '');
e = e.replace(/\$$/, '').replace(/\}$/, '').trim();
if (e.startsWith('.')) e = e.slice(1);
if (!e) return undefined;
return parsePath(json, e);
}
const JSON_TOKEN_RE = /(\$json:[^$]+\$|\{json:[^}]+\})/gi;
function resolveResponseTemplate(tpl, json) {
const s = String(tpl == null ? '' : tpl);
if (!s) return { text: '', touched: false };
let touched = false;
const text = s.replace(JSON_TOKEN_RE, (_m, token) => {
touched = true;
const v = jsonValue(json, token);
return v == null ? '' : String(v);
});
return { text, touched };
}
function firstUrlInText(text) {
if (!text) return '';
const m = String(text).match(/https?:\/\/[^\s"'<>\\]+/i);
return m ? m[0] : '';
}
function fillTemplate(tpl, file, extra) {
const s = String(tpl);
if (!s.includes('{{')) return s;
const name = file.name || 'image.png';
const dot = name.lastIndexOf('.');
const ext = dot > -1 ? name.slice(dot + 1) : '';
return s
.replace(/\{\{filename\}\}/g, name)
.replace(/\{\{rawfilename\}\}/g, name)
.replace(/\{\{ext\}\}/g, ext)
.replace(/\{\{mime\}\}/g, file.type || 'application/octet-stream')
.replace(/\{\{timestamp\}\}/g, String(Date.now()))
.replace(/\{\{random\}\}/g, Math.random().toString(36).slice(2, 10))
.replace(/\{\{site\}\}/g, (extra && extra.site ? extra.site : ''));
}
function buildUploadUrl(provider, file, site) {
let url = String(provider.uploadUrl || '').trim();
if (!url) throw new Error('图床未配置上传地址');
url = fillTemplate(url, file, { site });
const params = [];
for (const q of (provider.query || [])) {
if (!q || !q.key) continue;
const key = fillTemplate(q.key, file, { site });
const val = fillTemplate(q.value == null ? '' : q.value, file, { site });
params.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
}
if (params.length) url += (url.includes('?') ? '&' : '?') + params.join('&');
return url;
}
function hasHeader(headers, name) {
const lower = name.toLowerCase();
return Object.keys(headers).some((k) => k.toLowerCase() === lower);
}
function xhrRequest(opts) {
return new Promise((resolve, reject) => {
if (!hasGMXHR) { reject(new Error('缺少 GM_xmlhttpRequest 权限')); return; }
let finished = false;
const done = (fn, v) => { if (!finished) { finished = true; fn(v); } };
try {
GMXHR({
method: opts.method || 'POST',
url: opts.url,
headers: opts.headers || {},
data: opts.data,
timeout: opts.timeout || 30000,
withCredentials: !!opts.withCredentials,
onload: (res) => done(resolve, res),
onerror: () => done(reject, new Error('网络请求失败')),
ontimeout: () => done(reject, new Error('请求超时')),
onabort: () => done(reject, new Error('请求被取消')),
});
} catch (e) {
done(reject, e);
}
});
}
function readAsDataUrl(file) {
return new Promise((resolve, reject) => {
const fr = new FileReader();
fr.onload = () => resolve(String(fr.result || ''));
fr.onerror = () => reject(new Error('读取图片失败'));
fr.readAsDataURL(file);
});
}
async function uploadOnce(file, provider, site) {
const url = buildUploadUrl(provider, file, site);
const headers = safeAssign({}, provider.headers || {});
let body;
if (provider.bodyType === 'multipart') {
const fd = new FormData();
fd.append(provider.formField || 'file', file, file.name || 'image.png');
for (const f of (provider.fields || [])) {
if (!f || !f.key) continue;
fd.append(fillTemplate(f.key, file, { site }), fillTemplate(f.value == null ? '' : f.value, file, { site }));
}
body = fd;
} else if (provider.bodyType === 'base64json') {
const dataUrl = await readAsDataUrl(file);
const base64 = dataUrl.slice(dataUrl.indexOf(',') + 1);
if (!hasHeader(headers, 'content-type')) headers['Content-Type'] = 'application/json';
body = JSON.stringify({
filename: file.name || 'image.png',
content: base64,
mime: file.type || 'application/octet-stream',
});
} else {
body = file;
}
const res = await xhrRequest({
method: provider.method || 'POST',
url,
headers,
data: body,
timeout: provider.timeoutMs,
withCredentials: provider.withCredentials,
});
const text = res.responseText || '';
const status = res.status || 0;
if (status < 200 || status >= 300) {
let msg = 'HTTP ' + status;
try {
const j = JSON.parse(text);
if (j && (j.message || j.msg)) msg += ':' + (j.message || j.msg);
} catch (e) { /* ignore */ }
throw new Error(msg);
}
let json = null;
try { json = JSON.parse(text); } catch (e) { json = null; }
if (json && json.success === false) {
throw new Error(json.message || json.msg || json.code || '图床返回失败');
}
let imageUrl = '';
if (provider.urlPath) {
const r = resolveResponseTemplate(provider.urlPath, json);
imageUrl = r.touched ? r.text : (jsonValue(json, provider.urlPath) || '');
}
if (typeof imageUrl !== 'string' || !imageUrl) {
if (provider.urlRegex) {
try {
const m = text.match(new RegExp(provider.urlRegex));
if (m) imageUrl = m[1] || m[0];
} catch (e) { /* ignore */ }
}
}
if (typeof imageUrl !== 'string' || !imageUrl) {
imageUrl = firstUrlInText(text);
}
if (!imageUrl) throw new Error('无法从响应中解析出图片链接');
const safeUrl = safeHttpUrl(imageUrl);
if (!safeUrl) throw new Error('图床返回的链接不是 http/https:' + String(imageUrl).slice(0, 80));
imageUrl = safeUrl;
let deleteUrl = '';
if (provider.deleteUrlPath) {
const d = resolveResponseTemplate(provider.deleteUrlPath, json);
deleteUrl = d.touched ? d.text : (jsonValue(json, provider.deleteUrlPath) || '');
}
deleteUrl = safeHttpUrl(deleteUrl);
return { url: imageUrl, deleteUrl, raw: text, site: site || '' };
}
async function uploadWithRetry(file, provider, site) {
const retries = Math.max(0, Number(provider.retries) || 0);
let lastErr = null;
for (let i = 0; i <= retries; i++) {
try {
return await uploadOnce(file, provider, site);
} catch (e) {
lastErr = e;
const msg = String((e && e.message) || '');
if (/HTTP 4\d\d/.test(msg) && !/429/.test(msg)) break;
if (i < retries) await new Promise((r) => setTimeout(r, 600 * (i + 1)));
}
}
throw lastErr || new Error('上传失败');
}
function makeTestFile() {
const b64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
const bin = atob(b64);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return new File([bytes], 'piu-test.png', { type: 'image/png' });
}
/* =========================================================================
* 4. 插入到输入框
* ========================================================================= */
const TEXT_INPUT_TYPES = new Set(['text', 'search', 'url', 'email', 'tel']);
function isTextInput(el) {
if (!el || el.nodeType !== 1) return false;
if (el.tagName === 'TEXTAREA') return true;
if (el.tagName === 'INPUT') {
return TEXT_INPUT_TYPES.has((el.type || 'text').toLowerCase());
}
return false;
}
function isEditable(el) {
if (isTextInput(el)) return true;
if (!el || el.nodeType !== 1) return false;
if (el.isContentEditable === true) return true;
const doc = el.ownerDocument;
return !!(doc && doc.designMode && String(doc.designMode).toLowerCase() === 'on');
}
function findEditable(target) {
let el = target && target.nodeType === 1 ? target : (target && target.parentElement);
while (el) {
if (isEditable(el)) return el;
el = el.parentElement;
}
return null;
}
function editableRoot(el) {
if (!el) return null;
if (el.isContentEditable) return el.closest('[contenteditable]') || el;
return el;
}
function isBlockedInput(el) {
if (!el || el.nodeType !== 1) return true;
if (el.disabled || el.readOnly) return true;
if (el.tagName === 'INPUT' && String(el.type).toLowerCase() === 'password') return true;
return false;
}
function formatLink(url, filename, mode) {
const rawName = String(filename || '');
switch (mode) {
case 'markdown': return '![' + rawName.replace(/[[\]]/g, '\\$&') + '](' + url + ')';
case 'bbcode': return '[img]' + url + '[/img]';
case 'html': return '';
default: return url;
}
}
function insertTextInto(el, text) {
const doc = el.ownerDocument || document;
el.focus({ preventScroll: true });
if (isTextInput(el)) {
let ok = false;
try { ok = doc.execCommand('insertText', false, text); } catch (e) { ok = false; }
if (ok && el.value.includes(text)) return true;
const start = el.selectionStart == null ? el.value.length : el.selectionStart;
const end = el.selectionEnd == null ? start : el.selectionEnd;
try {
el.setRangeText(text, start, end, 'end');
} catch (e) {
setInputValue(el, el.value.slice(0, start) + text + el.value.slice(end));
return true;
}
el.dispatchEvent(new Event('input', { bubbles: true }));
return true;
}
try {
if (doc.execCommand('insertText', false, text)) return true;
} catch (e) { /* ignore */ }
return insertNodeInto(el, doc.createTextNode(text));
}
function insertNodeInto(el, domNode) {
const doc = el.ownerDocument || document;
el.focus({ preventScroll: true });
const sel = doc.getSelection ? doc.getSelection() : window.getSelection();
if (!sel || !sel.rangeCount) {
el.appendChild(domNode);
el.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' }));
return true;
}
const range = sel.getRangeAt(0);
if (!el.contains(range.commonAncestorContainer)) {
el.appendChild(domNode);
el.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' }));
return true;
}
range.deleteContents();
range.insertNode(domNode);
range.setStartAfter(domNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
el.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' }));
return true;
}
function setInputValue(el, value) {
const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
const desc = Object.getOwnPropertyDescriptor(proto, 'value');
if (desc && desc.set) desc.set.call(el, value);
else el.value = value;
el.dispatchEvent(new Event('input', { bubbles: true }));
}
function replaceInInput(el, token, text) {
const val = el.value;
const idx = val.indexOf(token);
if (idx === -1) return false;
const caret = el.selectionStart == null ? idx : el.selectionStart;
const next = val.slice(0, idx) + text + val.slice(idx + token.length);
setInputValue(el, next);
let caretNext = caret;
if (caret > idx) caretNext = Math.max(idx, caret - token.length + text.length);
try { el.setSelectionRange(caretNext, caretNext); } catch (e) { /* ignore */ }
return true;
}
function replaceInContentEditable(root, token, text, url, mode, filename) {
const doc = root.ownerDocument || document;
const walker = doc.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
let tn;
while ((tn = walker.nextNode())) {
const value = tn.nodeValue || '';
const idx = value.indexOf(token);
if (idx === -1) continue;
const before = value.slice(0, idx);
const after = value.slice(idx + token.length);
if (mode === 'html' && url) {
const frag = doc.createDocumentFragment();
if (before) frag.appendChild(doc.createTextNode(before));
const img = doc.createElement('img');
img.src = url;
img.alt = filename || '';
frag.appendChild(img);
if (after) frag.appendChild(doc.createTextNode(after));
tn.parentNode.replaceChild(frag, tn);
} else {
tn.nodeValue = before + text + after;
}
root.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' }));
return true;
}
return false;
}
/* =========================================================================
* 5. 站点规则
* ========================================================================= */
function matchHost(pattern, host) {
if (!pattern) return false;
const p = String(pattern).trim().toLowerCase();
host = String(host || '').toLowerCase();
if (!p) return false;
if (p === '*') return true;
if (p.startsWith('*.')) {
const base = p.slice(2);
return host === base || host.endsWith('.' + base);
}
return host === p || host.endsWith('.' + p);
}
const CONNECT_PATTERNS = (() => {
try {
const list = GM_info && GM_info.script && GM_info.script.meta && GM_info.script.meta.connect;
const arr = Array.isArray(list) ? list : String(list || '').split(/[\s,]+/);
return arr.map((s) => String(s).trim().toLowerCase()).filter(Boolean);
} catch (e) { return []; }
})();
function hostAllowed(host) {
if (!host) return false;
if (!CONNECT_PATTERNS.length) return true;
const h = String(host).toLowerCase();
return CONNECT_PATTERNS.some((p) => matchHost(p, h));
}
function allowHint(url) {
try {
const host = new URL(url).hostname;
if (!hostAllowed(host)) {
return '\n\n提示:域名 ' + host + ' 不在 @connect 白名单中,请在脚本头部添加 // @connect ' + host + ' 后刷新页面。';
}
} catch (e) { /* ignore */ }
return '';
}
function parseRule(rule) {
const text = String(rule || '').trim();
if (!text) return null;
const m = text.match(/^(\S+)(?:\s+([\s\S]+))?$/);
if (!m) return null;
let host = m[1];
if (host !== '*') {
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(host)) {
try { host = new URL(host).hostname; } catch (e) { /* ignore */ }
} else {
host = host.replace(/^\/+/, '').replace(/[/?#].*$/, '').replace(/:\d+$/, '');
}
}
if (!host) return null;
return { host, selector: (m[2] || '').trim() };
}
function matchRules(rules, host, el, allowScopedWithoutEl) {
let scopedHit = false;
for (const rule of rules) {
const r = parseRule(rule);
if (!r || !matchHost(r.host, host)) continue;
if (!r.selector) return { matched: true, scoped: false };
if (el && el.closest) {
try { if (el.closest(r.selector)) return { matched: true, scoped: true }; } catch (e) { /* ignore */ }
} else if (allowScopedWithoutEl) {
scopedHit = true;
}
}
return { matched: scopedHit, scoped: scopedHit };
}
// 白名单 > 黑名单:el 为空且 pageLevel=true 时用于悬浮球显示和规则预览
function siteRule(host, cfg, el, pageLevel) {
const wl = matchRules(cfg.whitelist, host, el, !!pageLevel);
if (wl.matched) {
return { upload: true, scoped: wl.scoped, reason: wl.scoped ? '命中白名单(限定选择器)' : '命中白名单' };
}
const bl = matchRules(cfg.blacklist, host, el, false);
if (bl.matched) {
return { upload: false, scoped: bl.scoped, reason: bl.scoped ? '命中黑名单(限定选择器)' : '命中黑名单' };
}
return { upload: true, scoped: false, reason: '黑名单未覆盖该站点' };
}
function shouldShowFab() {
if (!IS_TOP || !state.config || state.config.showFab === false) return false;
if (state.ui.panel && !state.ui.panel.hidden) return false;
return siteEnabled(HOST) && siteRule(HOST, state.config, null, true).upload;
}
/* =========================================================================
* 6. Toast
* ========================================================================= */
function toast(opts) {
if (!ensureUI()) return;
const root = state.ui.toasts;
if (!root) return;
const id = ++state.toastSeq;
const box = node('div', 'piu-toast ' + (opts.type || 'info'));
box.dataset.id = String(id);
const msg = node('div', 'piu-toast-msg', opts.message || '');
box.appendChild(msg);
if (opts.actions && opts.actions.length) {
const actWrap = node('div', 'piu-toast-actions');
for (const a of opts.actions) {
const b = node('button', 'piu-toast-btn', a.label);
b.addEventListener('click', () => {
try { a.onClick && a.onClick(); } catch (e) { console.warn(e); }
if (a.keepOpen !== true) box.remove();
});
actWrap.appendChild(b);
}
box.appendChild(actWrap);
}
root.appendChild(box);
requestAnimationFrame(() => box.classList.add('show'));
const timeout = opts.timeout == null ? 4000 : opts.timeout;
if (timeout > 0) {
setTimeout(() => {
box.classList.remove('show');
setTimeout(() => box.remove(), 220);
}, timeout);
}
while (root.children.length > 4) root.firstElementChild.remove();
return box;
}
/* =========================================================================
* 7. 面板 UI(懒加载挂载)
* ========================================================================= */
const CSS = `
:host { all: initial; }
*, *::before, *::after { box-sizing: border-box; }
.piu-layer { position: fixed; inset: 0; pointer-events: none; z-index: 2147483646; font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; color: var(--fg); }
.piu-layer > * { pointer-events: auto; }
.piu-root {
--bg: #ffffff; --bg2: #f6f7f9; --fg: #1f2328; --muted: #6b7280; --line: #e5e7eb;
--acc: #2563eb; --acc-fg: #ffffff; --danger: #dc2626; --ok: #059669;
--shadow: 0 18px 50px rgba(15, 23, 42, .18);
}
@media (prefers-color-scheme: dark) {
.piu-root {
--bg: #17191d; --bg2: #1f2228; --fg: #e6e8eb; --muted: #9aa2ae; --line: #2c3037;
--acc: #3b82f6; --acc-fg: #ffffff; --danger: #f87171; --ok: #34d399;
--shadow: 0 18px 50px rgba(0, 0, 0, .55);
}
}
.piu-fab {
position: fixed; right: 18px; bottom: 18px; width: 40px; height: 40px; border-radius: 50%;
background: var(--acc); color: var(--acc-fg); border: 0; cursor: pointer; font-size: 14px;
font-weight: 700; box-shadow: 0 6px 18px rgba(0,0,0,.25); opacity: .86; transition: opacity .15s, transform .15s;
}
.piu-fab:hover { opacity: 1; transform: translateY(-1px); }
.piu-mask { position: fixed; inset: 0; background: rgba(15,23,42,.35); }
.piu-panel {
position: fixed; right: 16px; top: 16px; bottom: 16px; width: min(780px, calc(100vw - 32px));
background: var(--bg); border: 1px solid var(--line); border-radius: 14px; box-shadow: var(--shadow);
display: flex; flex-direction: column; overflow: hidden;
}
.piu-panel[hidden], .piu-mask[hidden] { display: none !important; }
.piu-panel.piu-drop { outline: 2px dashed var(--acc); outline-offset: -8px; }
.piu-head { display: flex; align-items: center; gap: 8px; padding: 12px 14px; border-bottom: 1px solid var(--line); background: var(--bg2); }
.piu-brand { font-weight: 700; font-size: 14px; }
.piu-ver { font-weight: 400; color: var(--muted); font-size: 11px; margin-left: 6px; }
.piu-head-actions { margin-left: auto; display: flex; gap: 6px; }
.piu-icon { border: 0; background: transparent; color: var(--muted); font-size: 16px; cursor: pointer; padding: 2px 6px; border-radius: 6px; }
.piu-icon:hover { background: var(--line); color: var(--fg); }
.piu-tabs { display: flex; gap: 4px; padding: 8px 14px 0; border-bottom: 1px solid var(--line); }
.piu-tab { border: 0; background: transparent; color: var(--muted); padding: 7px 12px; cursor: pointer; border-bottom: 2px solid transparent; font-size: 13px; }
.piu-tab.active { color: var(--acc); border-bottom-color: var(--acc); font-weight: 600; }
.piu-panes { flex: 1; overflow: hidden; display: flex; }
.piu-pane { flex: 1; overflow-y: auto; padding: 12px 14px 18px; }
.piu-pane[hidden] { display: none; }
.piu-toolbar { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 10px; }
.piu-toolbar select, .piu-toolbar input, .piu-field input, .piu-field select, .piu-field textarea {
background: var(--bg2); color: var(--fg); border: 1px solid var(--line); border-radius: 7px;
padding: 6px 8px; font: inherit; outline: none;
}
.piu-toolbar select:focus, .piu-toolbar input:focus, .piu-field input:focus, .piu-field textarea:focus { border-color: var(--acc); }
.piu-toolbar input { flex: 1; min-width: 120px; }
.piu-btn {
background: var(--acc); color: var(--acc-fg); border: 0; border-radius: 7px; padding: 6px 12px;
cursor: pointer; font: inherit;
}
.piu-btn:hover { filter: brightness(1.06); }
.piu-btn.ghost { background: var(--bg2); color: var(--fg); border: 1px solid var(--line); }
.piu-btn.danger { background: transparent; color: var(--danger); border: 1px solid var(--danger); }
.piu-btn:disabled { opacity: .55; cursor: default; }
.piu-view { display: flex; border: 1px solid var(--line); border-radius: 7px; overflow: hidden; }
.piu-view button { background: transparent; color: var(--muted); border: 0; padding: 6px 10px; font: inherit; font-size: 12px; cursor: pointer; }
.piu-view button.active { background: var(--acc); color: var(--acc-fg); }
.piu-list { display: flex; flex-direction: column; gap: 8px; }
.piu-item { display: flex; gap: 10px; align-items: flex-start; padding: 8px; border: 1px solid var(--line); border-radius: 10px; background: var(--bg2); }
.piu-thumb { width: 52px; height: 52px; object-fit: cover; border-radius: 7px; background: var(--line); flex: none; cursor: zoom-in; }
.piu-list.waterfall { display: block; column-width: 220px; column-gap: 8px; }
.piu-list.waterfall .piu-item { display: block; padding: 0; margin: 0 0 8px; break-inside: avoid; position: relative; overflow: hidden; }
.piu-list.waterfall .piu-thumb { width: 100%; height: auto; max-height: 320px; border-radius: 10px; display: block; }
.piu-list.waterfall .piu-info { display: none; }
.piu-list.waterfall .piu-empty { column-span: all; }
.piu-list.waterfall .piu-actions {
position: absolute; left: 0; right: 0; bottom: 0; max-width: none; justify-content: center;
padding: 18px 6px 6px; background: linear-gradient(to top, rgba(0, 0, 0, .62), transparent);
opacity: 0; pointer-events: none; transition: opacity .15s;
}
.piu-list.waterfall .piu-item:hover .piu-actions { opacity: 1; pointer-events: auto; }
.piu-list.waterfall .piu-actions button { background: rgba(0, 0, 0, .5); color: #fff; border-color: transparent; }
.piu-list.waterfall .piu-actions button:hover { border-color: #fff; color: #fff; }
.piu-list.waterfall .piu-actions button.danger:hover { border-color: var(--danger); color: #fff; }
@media (hover: none) { .piu-list.waterfall .piu-actions { opacity: 1; pointer-events: auto; } }
.piu-viewer { position: fixed; inset: 0; z-index: 5; background: rgba(0,0,0,.82); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; cursor: zoom-out; }
.piu-viewer[hidden] { display: none !important; }
.piu-viewer img { max-width: 92vw; max-height: 88vh; border-radius: 8px; box-shadow: 0 12px 40px rgba(0,0,0,.5); background: #fff; }
.piu-viewer-hint { color: #d9dde3; font-size: 12px; }
.piu-dialog { position: fixed; inset: 0; z-index: 8; background: rgba(15,23,42,.45); display: flex; align-items: center; justify-content: center; padding: 16px; }
.piu-dialog[hidden] { display: none !important; }
.piu-dialog-box { background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 12px; box-shadow: var(--shadow); width: min(440px, 100%); padding: 14px 16px; }
.piu-dialog-title { font-weight: 600; margin-bottom: 8px; }
.piu-dialog-msg { color: var(--fg); font-size: 13px; white-space: pre-wrap; word-break: break-word; max-height: 40vh; overflow: auto; }
.piu-dialog-input { width: 100%; min-height: 110px; margin-top: 10px; background: var(--bg2); color: var(--fg); border: 1px solid var(--line); border-radius: 7px; padding: 7px 8px; font: 12px/1.5 ui-monospace, Menlo, Consolas, monospace; resize: vertical; outline: none; }
.piu-dialog-input:focus { border-color: var(--acc); }
.piu-dialog-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 12px; }
.piu-btn.danger-solid { background: var(--danger); color: #fff; }
.piu-info { flex: 1; min-width: 0; }
.piu-url { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.piu-meta { color: var(--muted); font-size: 11px; margin-top: 3px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.piu-badge { display: inline-block; padding: 0 6px; border-radius: 999px; font-size: 10px; background: var(--line); color: var(--muted); }
.piu-actions { display: flex; gap: 4px; flex-wrap: wrap; justify-content: flex-end; max-width: 210px; flex: none; }
.piu-actions button { background: transparent; border: 1px solid var(--line); color: var(--fg); border-radius: 6px; padding: 3px 7px; font-size: 11px; cursor: pointer; }
.piu-actions button:hover { border-color: var(--acc); color: var(--acc); }
.piu-actions button.danger:hover { border-color: var(--danger); color: var(--danger); }
.piu-sentinel { text-align: center; color: var(--muted); font-size: 12px; padding: 14px 0; }
.piu-empty { text-align: center; color: var(--muted); padding: 40px 0; font-size: 13px; }
.piu-uploading { border-style: dashed; }
.piu-thumb-loading {
background: linear-gradient(90deg, var(--line) 25%, var(--bg) 50%, var(--line) 75%);
background-size: 200% 100%; animation: piu-shimmer 1.2s linear infinite;
}
.piu-marquee { overflow: hidden; white-space: nowrap; }
.piu-marquee span { display: inline-block; padding-left: 100%; animation: piu-marquee 4s linear infinite; }
@keyframes piu-marquee { from { transform: translateX(0); } to { transform: translateX(-100%); } }
@keyframes piu-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
.piu-list.waterfall .piu-item.piu-uploading { display: flex; gap: 10px; padding: 8px; }
.piu-list.waterfall .piu-item.piu-uploading .piu-thumb { width: 52px; height: 52px; }
.piu-list.waterfall .piu-item.piu-uploading .piu-info { display: block; }
.piu-group { border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; margin-bottom: 10px; }
.piu-group-title { font-weight: 600; margin-bottom: 8px; }
.piu-row { display: flex; align-items: center; gap: 8px; padding: 4px 0; }
.piu-row input[type=checkbox], .piu-row input[type=radio] { accent-color: var(--acc); }
.piu-radios { display: flex; gap: 14px; flex-wrap: wrap; padding: 2px 0 4px; }
.piu-radios label { display: flex; align-items: center; gap: 5px; cursor: pointer; }
.piu-field { display: block; margin: 6px 0; }
.piu-field > span { display: block; color: var(--muted); font-size: 11px; margin-bottom: 3px; }
.piu-field input, .piu-field select, .piu-field textarea { width: 100%; }
.piu-field textarea { resize: vertical; min-height: 54px; font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; }
.piu-hint { color: var(--muted); font-size: 11px; margin-top: 6px; }
.piu-hint a { color: var(--acc); text-decoration: none; }
.piu-hint a:hover { text-decoration: underline; }
.piu-about { text-align: center; padding: 18px 0 10px; }
.piu-about-logo { width: 48px; height: 48px; border-radius: 12px; background: var(--acc); color: var(--acc-fg); display: flex; align-items: center; justify-content: center; font-size: 20px; font-weight: 700; margin: 0 auto 10px; }
.piu-about-name { font-size: 16px; font-weight: 600; }
.piu-about-ver { color: var(--muted); font-size: 12px; margin-top: 2px; }
.piu-about-desc { color: var(--muted); font-size: 12px; margin-top: 8px; }
.piu-provider { border: 1px solid var(--line); border-radius: 10px; margin-bottom: 10px; background: var(--bg2); overflow: hidden; }
.piu-provider > summary { list-style: none; cursor: pointer; padding: 9px 12px; display: flex; align-items: center; gap: 8px; }
.piu-provider > summary::-webkit-details-marker { display: none; }
.piu-provider > summary .piu-name { font-weight: 600; }
.piu-provider > summary .piu-grow { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--muted); font-size: 11px; }
.piu-provider-body { padding: 4px 12px 12px; background: var(--bg); border-top: 1px solid var(--line); }
.piu-grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 0 12px; }
.piu-provider-actions { display: flex; gap: 6px; margin-top: 8px; flex-wrap: wrap; }
.piu-toasts { position: fixed; left: 16px; bottom: 16px; z-index: 6; display: flex; flex-direction: column; gap: 8px; max-width: min(420px, calc(100vw - 32px)); }
.piu-toast { background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-left: 3px solid var(--acc); border-radius: 9px; box-shadow: var(--shadow); padding: 9px 11px; opacity: 0; transform: translateY(6px); transition: opacity .2s, transform .2s; }
.piu-toast.show { opacity: 1; transform: none; }
.piu-toast.success { border-left-color: var(--ok); }
.piu-toast.error { border-left-color: var(--danger); }
.piu-toast-msg { word-break: break-all; }
.piu-toast-actions { display: flex; gap: 6px; margin-top: 7px; }
.piu-toast-btn { background: transparent; border: 1px solid var(--line); color: var(--fg); border-radius: 6px; padding: 3px 8px; font-size: 11px; cursor: pointer; }
.piu-toast-btn:hover { border-color: var(--acc); color: var(--acc); }
`;
const PANEL_HTML = `
',
};
function updateRuleVerdict() {
const root = state.shadow;
const verdict = root && root.getElementById('piu-rule-verdict');
if (!verdict) return;
if (!HOST) {
verdict.textContent = '本页判定:当前 frame 取不到域名,匹配不了白名单,按黑名单走原生粘贴。';
return;
}
const live = (id, fallback) => {
const el = root.getElementById(id);
return el ? splitLines(el.value) : (fallback || []);
};
const rule = siteRule(HOST, {
whitelist: live('piu-s-whitelist', state.config.whitelist),
blacklist: live('piu-s-blacklist', state.config.blacklist),
}, null, true);
const actionText = rule.upload
? (rule.scoped ? '匹配选择器的输入框会上传到图床' : '粘贴图片会上传到图床')
: '走原生粘贴,不碰图床';
verdict.textContent = '本页判定(' + HOST + '):' + actionText + ',原因:' + rule.reason + '。';
}
function renderSettings() {
if (!state.shadow) return;
const root = state.shadow;
const cfg = state.config;
root.getElementById('piu-s-enabled').checked = !!cfg.enabled;
root.getElementById('piu-s-autocopy').checked = !!cfg.autoCopy;
root.getElementById('piu-s-fab').checked = cfg.showFab !== false;
root.getElementById('piu-s-siteoff').checked = !siteEnabled(HOST);
root.getElementById('piu-s-host').textContent = HOST || '(未知)';
root.getElementById('piu-s-blacklist').value = (cfg.blacklist || []).join('\n');
root.getElementById('piu-s-whitelist').value = (cfg.whitelist || []).join('\n');
updateRuleVerdict();
root.querySelectorAll('input[name="piu-insert"]').forEach((r) => {
r.checked = r.value === cfg.insertMode;
});
root.getElementById('piu-insert-hint').textContent = INSERT_HINTS[cfg.insertMode] || '';
const w = cfg.webdav || {};
root.getElementById('piu-w-url').value = w.url || '';
root.getElementById('piu-w-user').value = w.username || '';
root.getElementById('piu-w-pass').value = w.password || '';
root.getElementById('piu-w-folder').value = w.folder == null ? DEFAULT_DAV_FOLDER : w.folder;
root.getElementById('piu-w-file').value = w.file || DEFAULT_DAV_FILE;
root.getElementById('piu-w-auto').checked = !!w.auto;
}
function onSettingsChange(e) {
const t = e.target;
if (!t) return;
const cfg = state.config;
if (t.id === 'piu-s-enabled') cfg.enabled = t.checked;
else if (t.id === 'piu-s-autocopy') cfg.autoCopy = t.checked;
else if (t.id === 'piu-s-fab') cfg.showFab = t.checked;
else if (t.id === 'piu-s-siteoff') cfg.siteEnabled[HOST] = !t.checked;
else if (t.id === 'piu-s-blacklist') cfg.blacklist = splitLines(t.value);
else if (t.id === 'piu-s-whitelist') cfg.whitelist = splitLines(t.value);
else if (t.id === 'piu-w-url') cfg.webdav.url = t.value.trim();
else if (t.id === 'piu-w-user') cfg.webdav.username = t.value.trim();
else if (t.id === 'piu-w-pass') cfg.webdav.password = t.value;
else if (t.id === 'piu-w-folder') cfg.webdav.folder = t.value.trim();
else if (t.id === 'piu-w-file') cfg.webdav.file = t.value.trim() || DEFAULT_DAV_FILE;
else if (t.id === 'piu-w-auto') cfg.webdav.auto = t.checked;
else if (t.name === 'piu-insert') {
cfg.insertMode = t.value;
state.shadow.getElementById('piu-insert-hint').textContent = INSERT_HINTS[t.value] || '';
refreshCopyFormatLabels();
} else return;
saveConfig();
if (t.id === 'piu-s-fab' || t.id === 'piu-s-siteoff' || t.id === 'piu-s-blacklist' || t.id === 'piu-s-whitelist') {
applyFabVisibility();
}
if (t.id === 'piu-s-blacklist' || t.id === 'piu-s-whitelist') updateRuleVerdict();
}
function splitLines(text) {
return String(text || '').split('\n').map((s) => s.trim()).filter(Boolean);
}
function syncUIAfterConfigChange() {
renderSettings();
renderProviders();
refreshProviderOptions();
applyHistoryView();
applyFabVisibility();
}
function resetConfigToDefault() {
state.config = defaultConfig();
saveConfig();
state.list.filters = { siteHost: '', providerId: '', q: '' };
if (state.shadow) {
const fSite = state.shadow.getElementById('piu-f-site');
const fProvider = state.shadow.getElementById('piu-f-provider');
const fQuery = state.shadow.getElementById('piu-f-q');
if (fSite) fSite.selectedIndex = 0;
if (fProvider) fProvider.selectedIndex = 0;
if (fQuery) fQuery.value = '';
}
syncUIAfterConfigChange();
}
async function onSettingsClick(e) {
const btn = e.target.closest('button[data-act]');
if (!btn) return;
const act = btn.dataset.act;
if (act === 'export-config') exportConfig();
else if (act === 'import-config') importConfig();
else if (act === 'export-history') exportHistory();
else if (act === 'import-history') importHistory();
else if (act === 'webdav-test' || act === 'webdav-backup' || act === 'webdav-restore') {
btn.disabled = true;
try {
if (act === 'webdav-test') {
toast({ type: 'success', message: await webdavTest(), timeout: 6000 });
} else if (act === 'webdav-backup') {
await webdavBackup();
} else {
await webdavRestore();
}
} catch (err) {
const prefix = act === 'webdav-test' ? '连接失败:' : (act === 'webdav-backup' ? '备份失败:' : '恢复失败:');
toast({ type: 'error', message: prefix + (err.message || err) + webdavAllowHint(), timeout: 9000 });
} finally {
btn.disabled = false;
}
} else if (act === 'reset-config') {
if (!(await uiConfirm('恢复默认设置?图床、站点规则、WebDAV 等配置会重置为初始值,历史记录保留。', {
title: '恢复默认设置', okText: '恢复默认', danger: true,
}))) return;
resetConfigToDefault();
refreshSiteOptions();
toast({ type: 'success', message: '已恢复默认设置,历史记录已保留' });
} else if (act === 'clear-history') {
if (!(await uiConfirm('清空所有历史记录?该操作不可恢复。', {
title: '清空历史记录', okText: '清空', danger: true,
}))) return;
await History.clear();
refreshSiteOptions();
reloadHistory();
toast({ type: 'success', message: '历史记录已清空' });
} else if (act === 'clear-all') {
if (!(await uiConfirm('重置全部数据(配置 + 历史记录)?该操作不可恢复。', {
title: '重置全部数据', okText: '重置', danger: true,
}))) return;
await History.clear();
resetConfigToDefault();
refreshSiteOptions();
reloadHistory();
toast({ type: 'success', message: '已重置' });
}
}
function exportConfig() {
const payload = {
type: 'piu-config',
schemaVersion: state.config.schemaVersion || 1,
exportedAt: new Date().toISOString(),
config: state.config,
};
download('粘贴即传图-配置-' + stamp() + '.json', JSON.stringify(payload, null, 2));
const w = state.config.webdav || {};
const hasSecret = state.config.providers.some((p) => Object.keys(p.headers || {}).length) || !!w.password;
if (hasSecret) {
toast({ type: 'info', message: '注意:配置中包含图床 token / WebDAV 密码,请妥善保管', timeout: 6000 });
}
}
function importConfig() {
pickFile('.json,application/json', async (text) => {
let j;
try { j = JSON.parse(text); } catch (e) { toast({ type: 'error', message: 'JSON 解析失败' }); return; }
const cfg = j && j.config ? j.config : j;
if (!cfg || !Array.isArray(cfg.providers)) {
toast({ type: 'error', message: '不是有效的配置文件' });
return;
}
if (!(await uiConfirm('导入将覆盖当前配置(历史记录不受影响),继续?', {
title: '导入配置', okText: '覆盖导入', danger: true,
}))) return;
state.config = normalizeConfig(cfg);
saveConfig();
syncUIAfterConfigChange();
toast({ type: 'success', message: '配置已导入' });
});
}
async function exportHistory() {
const fmt = state.shadow.getElementById('piu-export-fmt').value;
const all = await History.all();
if (!all.length) { toast({ type: 'info', message: '暂无历史记录' }); return; }
const base = '粘贴即传图-历史-' + stamp();
if (fmt === 'json') {
download(base + '.json', JSON.stringify({ type: 'piu-history', exportedAt: new Date().toISOString(), records: all }, null, 2));
} else if (fmt === 'csv') {
const rows = [['url', 'deleteUrl', 'siteHost', 'providerName', 'filename', 'size', 'status', 'createdAt']];
for (const r of all) {
rows.push([
r.url, r.deleteUrl || '', r.siteHost || '', r.providerName || '',
r.filename || '', r.size || '', r.status || '', new Date(r.createdAt).toISOString(),
]);
}
const csv = rows.map((row) => row.map(csvCell).join(',')).join('\r\n');
download(base + '.csv', '\ufeff' + csv, 'text/csv;charset=utf-8');
} else if (fmt === 'md') {
const md = all.map((r) => '- [' + (r.filename || 'image') + '](' + r.url + ') · ' + (r.siteHost || '') + ' · ' + fmtTime(r.createdAt)).join('\n');
download(base + '.md', md, 'text/markdown;charset=utf-8');
} else {
download(base + '.txt', all.map((r) => r.url).join('\n'), 'text/plain;charset=utf-8');
}
toast({ type: 'success', message: '已导出 ' + all.length + ' 条记录' });
}
function csvCell(v) {
const s = String(v == null ? '' : v);
return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
}
function importHistory() {
pickFile('.json,application/json', async (text) => {
let j;
try { j = JSON.parse(text); } catch (e) { toast({ type: 'error', message: 'JSON 解析失败' }); return; }
const records = Array.isArray(j) ? j : (j && j.records);
if (!Array.isArray(records)) { toast({ type: 'error', message: '文件中没有 records 数组' }); return; }
if (!(await uiConfirm('将导入 ' + records.length + ' 条记录(与现有记录合并去重),继续?', {
title: '导入历史记录', okText: '导入',
}))) return;
const { added, skipped, duplicated } = await History.merge(records, {
defaultInsertedAs: state.config.insertMode,
});
refreshSiteOptions();
reloadHistory();
const extra = [];
if (duplicated) extra.push('重复 ' + duplicated + ' 条');
if (skipped) extra.push('无效 ' + skipped + ' 条');
toast({
type: 'success',
message: '已导入 ' + added + ' 条记录' + (extra.length ? '(跳过' + extra.join('、') + ')' : ''),
});
});
}
/* ---------------- WebDAV 备份 ---------------- */
function b64utf8(str) {
try {
const bytes = new TextEncoder().encode(String(str));
let bin = '';
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
return btoa(bin);
} catch (e) {
try { return btoa(unescape(encodeURIComponent(String(str)))); } catch (e2) { return ''; }
}
}
function normalizeDavBase(raw) {
let u = String(raw || '').trim();
if (!u) throw new Error('请先填写 WebDAV 地址');
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(u)) u = 'https://' + u.replace(/^\/+/, '');
if (!/^https?:\/\//i.test(u)) throw new Error('WebDAV 地址只支持 http/https');
return u.replace(/\/+$/, '');
}
function sanitizeDavSegments(str) {
return String(str == null ? '' : str)
.split('/')
.map((s) => s.trim())
.filter((s) => s && s !== '.' && s !== '..');
}
function encodeDavPath(segments) {
return segments.map((s) => encodeURIComponent(s)).join('/');
}
function webdavTarget() {
const w = state.config.webdav || {};
const base = normalizeDavBase(w.url);
const folderSegs = sanitizeDavSegments(w.folder == null ? DEFAULT_DAV_FOLDER : w.folder);
const finalFolder = folderSegs.length ? folderSegs : [DEFAULT_DAV_FOLDER];
const fileSegs = sanitizeDavSegments(w.file || DEFAULT_DAV_FILE);
if (!fileSegs.length) throw new Error('WebDAV 文件名不能为空');
const allSegs = finalFolder.concat(fileSegs);
return {
base,
parentSegs: allSegs.slice(0, -1),
url: base + '/' + encodeDavPath(allSegs),
};
}
function webdavAllowHint() {
try { return allowHint(webdavTarget().url); } catch (e) { return ''; }
}
function webdavHeaders(extra) {
const w = state.config.webdav || {};
const headers = Object.assign({}, extra || {});
if (w.username) headers.Authorization = 'Basic ' + b64utf8(w.username + ':' + (w.password || ''));
return headers;
}
async function webdavTest() {
const target = webdavTarget();
const res = await xhrRequest({ method: 'PROPFIND', url: target.url, headers: webdavHeaders({ Depth: '0' }), timeout: 15000 });
if (res.status === 401 || res.status === 403) throw new Error('认证失败(HTTP ' + res.status + ')');
if (res.status === 404) return '服务器可访问:' + target.url + '(文件尚不存在,首次备份会自动创建目录)';
if (res.status === 405) return '服务器可访问(该服务器不支持 PROPFIND)';
if (res.status >= 200 && res.status < 300) return '连接成功,认证通过';
throw new Error('HTTP ' + res.status);
}
async function ensureDavParents(target) {
let cur = target.base;
for (const seg of target.parentSegs) {
cur += '/' + encodeURIComponent(seg);
try {
const res = await xhrRequest({ method: 'MKCOL', url: cur, headers: webdavHeaders(), timeout: 15000 });
if (res.status === 401 || res.status === 403) return false;
} catch (e) {
return false;
}
}
return true;
}
async function webdavBackup(opts) {
const silent = !!(opts && opts.silent);
const target = webdavTarget();
const records = await History.all();
const payload = {
type: 'piu-backup',
schemaVersion: 1,
appVersion: VERSION,
exportedAt: new Date().toISOString(),
config: state.config,
records,
};
const body = JSON.stringify(payload, null, 2);
const byteSize = new Blob([body]).size;
const put = () => xhrRequest({
method: 'PUT',
url: target.url,
headers: webdavHeaders({ 'Content-Type': 'application/json;charset=utf-8' }),
data: body,
timeout: 30000,
});
let res = await put();
if (res.status === 404 || res.status === 409) {
if (await ensureDavParents(target)) res = await put();
}
if (res.status === 401 || res.status === 403) throw new Error('认证失败(HTTP ' + res.status + ')');
if (res.status < 200 || res.status >= 300) throw new Error('HTTP ' + res.status);
if (!silent) {
toast({ type: 'success', message: '备份完成:' + records.length + ' 条记录,' + fmtBytes(byteSize), timeout: 6000 });
}
return { count: records.length, bytes: byteSize, url: target.url };
}
async function webdavRestore() {
const target = webdavTarget();
const res = await xhrRequest({ method: 'GET', url: target.url, headers: webdavHeaders(), timeout: 30000 });
if (res.status === 401 || res.status === 403) throw new Error('认证失败(HTTP ' + res.status + ')');
if (res.status === 404) throw new Error('备份文件不存在');
if (res.status < 200 || res.status >= 300) throw new Error('HTTP ' + res.status);
let j;
try { j = JSON.parse(res.responseText || ''); } catch (e) { throw new Error('备份文件不是有效 JSON'); }
const cfg = j && !Array.isArray(j) ? j.config : null;
const records = Array.isArray(j) ? j : (j && j.records);
if (!cfg && !Array.isArray(records)) throw new Error('备份文件格式不正确');
const tips = [];
if (cfg) tips.push('图床与设置将被覆盖');
if (Array.isArray(records)) tips.push('合并 ' + records.length + ' 条历史记录');
if (!(await uiConfirm('从 WebDAV 恢复备份?\n' + tips.join(';') + '。\n\n继续?', {
title: '从备份恢复', okText: '恢复', danger: true,
}))) return;
if (cfg && Array.isArray(cfg.providers)) {
state.config = normalizeConfig(cfg);
saveConfig();
syncUIAfterConfigChange();
}
let added = 0;
let skipped = 0;
if (Array.isArray(records)) {
const r = await History.merge(records, { defaultInsertedAs: state.config.insertMode });
added = r.added;
skipped = r.skipped;
}
if (state.ui.panel && !state.ui.panel.hidden && !state.shadow.querySelector('[data-pane="history"]').hidden) {
refreshSiteOptions();
reloadHistory();
}
toast({
type: 'success',
message: '恢复完成:配置已更新,新增 ' + added + ' 条历史记录' + (skipped ? ',跳过 ' + skipped + ' 条无效链接' : ''),
timeout: 6000,
});
}
let autoBackupTimer = null;
function scheduleAutoBackup() {
const w = state.config.webdav || {};
if (!w.auto || !w.url) return;
clearTimeout(autoBackupTimer);
autoBackupTimer = setTimeout(() => {
webdavBackup({ silent: true }).catch(() => { /* 自动备份失败时静默 */ });
}, 5000);
}
function pickFile(accept, cb) {
const input = document.createElement('input');
input.type = 'file';
input.accept = accept;
input.style.display = 'none';
const cleanup = () => {
window.removeEventListener('focus', onFocus);
input.remove();
};
const onFocus = () => setTimeout(() => {
if (!input.files || !input.files.length) cleanup();
}, 400);
input.addEventListener('cancel', cleanup, { once: true });
input.addEventListener('change', () => {
const file = input.files && input.files[0];
if (!file) { cleanup(); return; }
const fr = new FileReader();
fr.onload = () => { cb(String(fr.result || '')); cleanup(); };
fr.onerror = () => { toast({ type: 'error', message: '读取文件失败' }); cleanup(); };
fr.readAsText(file);
}, { once: true });
document.body.appendChild(input);
window.addEventListener('focus', onFocus, { once: true });
input.click();
}
function stamp() {
const d = new Date();
return d.getFullYear() + pad2(d.getMonth() + 1) + pad2(d.getDate()) + '-' + pad2(d.getHours()) + pad2(d.getMinutes()) + pad2(d.getSeconds());
}
/* =========================================================================
* 8. 粘贴处理
* ========================================================================= */
let pasteMods = { shift: false, alt: false };
let modsTimer = null;
let lastPaste = { sig: '', at: 0, target: null };
function trackMods(e) {
const isV = e.code === 'KeyV' || String(e.key || '').toLowerCase() === 'v';
if (!isV) return;
pasteMods = { shift: !!e.shiftKey, alt: !!e.altKey };
clearTimeout(modsTimer);
modsTimer = setTimeout(() => { pasteMods = { shift: false, alt: false }; }, 800);
if (e.altKey && !e.ctrlKey && !e.metaKey) {
e.preventDefault();
if (e.stopImmediatePropagation) e.stopImmediatePropagation();
else if (e.stopPropagation) e.stopPropagation();
uploadFromClipboard(e.target);
}
}
async function uploadFromClipboard(target) {
const cfg = state.config;
if (!cfg || !cfg.enabled) return;
const editable = findEditable(target);
if (!editable) {
toast({ type: 'error', message: '先把光标放进输入框,再按 Alt+V' });
return;
}
if (!siteEnabled(HOST)) {
toast({ type: 'error', message: HOST + ' 已在设置中禁用' });
return;
}
if (!navigator.clipboard || !navigator.clipboard.read) {
toast({ type: 'error', message: '当前浏览器不支持主动读剪贴板,请改用 Ctrl+V 粘贴' });
return;
}
let items = [];
try {
items = await navigator.clipboard.read();
} catch (e) {
toast({ type: 'error', message: '读取剪贴板被拒绝(需浏览器授权),请改用 Ctrl+V 粘贴' });
return;
}
const files = [];
for (const item of items) {
for (const type of item.types || []) {
if (!/^image\//i.test(type)) continue;
const blob = await item.getType(type);
const ext = (type.split('/')[1] || 'png').replace(/[^a-z0-9]/gi, '') || 'png';
files.push(new File([blob], 'clipboard.' + ext, { type }));
}
}
if (!files.length) {
toast({ type: 'info', message: '剪贴板里没有图片' });
return;
}
handleImageFiles(files, editable);
}
function getImageFiles(cd) {
const out = [];
const seen = new Set();
if (!cd) return out;
const add = (f) => {
if (!f || !/^image\//i.test(f.type || '')) return;
const sig = [f.name || '', f.size || 0, f.type || ''].join('|');
if (seen.has(sig)) return;
seen.add(sig);
out.push(f);
};
if (cd.items && cd.items.length) {
for (let i = 0; i < cd.items.length; i++) {
const item = cd.items[i];
if (!item || item.kind !== 'file' || !/^image\//i.test(item.type || '')) continue;
add(item.getAsFile && item.getAsFile());
}
}
if (!out.length && cd.files && cd.files.length) {
for (let i = 0; i < cd.files.length; i++) add(cd.files[i]);
}
return out;
}
function validateFile(file, provider) {
if (!/^image\//i.test(file.type || '')) return '不是图片文件';
const maxMB = Number(provider.maxSizeMB) > 0 ? Number(provider.maxSizeMB) : 5;
if (file.size > maxMB * 1024 * 1024) {
return '图片超过 ' + maxMB + ' MB(' + fmtBytes(file.size) + ')';
}
if (!file.size) return '图片为空';
return '';
}
async function handleImageFiles(files, editable) {
const provider = activeProvider();
if (!provider) {
toast({ type: 'error', message: '没有可用的图床,请先在面板中配置' });
return;
}
if (!provider.uploadUrl) {
toast({ type: 'error', message: '当前图床未填写上传地址' });
return;
}
const mode = state.config.insertMode || 'url';
const root = editable ? editableRoot(editable) : null;
const tasks = [];
let seq = 0;
for (const file of files) {
const err = validateFile(file, provider);
if (err) {
toast({ type: 'error', message: (file.name || '图片') + ':' + err });
continue;
}
let token = '';
let ph = null;
if (root) {
token = '[上传中…]' + ZWSP.repeat(seq + 1);
seq++;
insertTextInto(root, token);
} else if (state.ui.panel && !state.ui.panel.hidden) {
ph = addUploadPlaceholder(file.name);
}
tasks.push({ file, token, ph });
}
if (!tasks.length) return;
await pool(tasks, 2, async (task) => {
const { file, token, ph } = task;
const filename = file.name || 'image.png';
try {
const result = await uploadWithRetry(file, provider, HOST);
if (root) {
const text = formatLink(result.url, filename, mode);
const isRich = !isTextInput(root);
const replaced = isRich
? replaceInContentEditable(root, token, text, result.url, mode, filename)
: replaceInInput(root, token, text);
if (!replaced) {
if (isRich && mode === 'html') {
const doc = root.ownerDocument || document;
const img = doc.createElement('img');
img.src = result.url;
img.alt = filename;
insertNodeInto(root, img);
} else {
insertTextInto(root, text);
}
}
}
const rec = {
id: uuid(),
url: result.url,
deleteUrl: result.deleteUrl || '',
providerId: provider.id,
providerName: provider.name,
pageUrl: (/^about:/.test(location.href) ? (document.referrer || location.href) : location.href).slice(0, 2000),
pageTitle: (document.title || '').slice(0, 200),
siteHost: HOST || location.hostname,
filename,
mime: file.type || '',
size: file.size || 0,
insertedAs: mode,
status: 'ok',
};
await History.add(rec);
scheduleAutoBackup();
if (state.config.autoCopy) await copyText(result.url);
toast({
type: 'success',
message: root ? '已上传并插入链接' : '已上传到图床',
actions: [
{ label: '复制链接', keepOpen: false, onClick: () => copyText(result.url) },
{ label: '查看历史', keepOpen: false, onClick: () => openPanel('history') },
],
});
if (ph) ph.remove();
if (state.ui.panel && !state.ui.panel.hidden && !state.shadow.querySelector('[data-pane="history"]').hidden) {
state.list.items.unshift(rec);
if (state.ui.listEl.querySelector('.piu-empty')) state.ui.listEl.innerHTML = '';
state.ui.listEl.insertAdjacentHTML('afterbegin', recordItemHtml(rec));
}
} catch (err) {
if (ph) ph.remove();
if (root) {
if (!isTextInput(root)) replaceInContentEditable(root, token, '', '', 'url', '');
else replaceInInput(root, token, '');
}
const msg = (err && err.message) || String(err);
toast({
type: 'error',
message: '上传失败:' + msg + allowHint(provider.uploadUrl),
timeout: 8000,
actions: [{ label: '打开图床设置', keepOpen: false, onClick: () => openPanel('providers') }],
});
}
});
}
function pasteSkip(reason) {
console.info('[粘贴即传图] 未上传:' + reason);
}
function onPaste(e) {
const cfg = state.config;
if (!cfg || !cfg.enabled) return;
if (state.hostEl && e.composedPath && e.composedPath().includes(state.hostEl)) return;
const files = getImageFiles(e.clipboardData);
if (!files.length) return;
const editable = findEditable(e.target);
if (!editable) return pasteSkip('粘贴目标不是可编辑元素');
if (isBlockedInput(editable)) return pasteSkip('目标输入框只读 / 禁用 / 密码框');
if (!siteEnabled(HOST)) return pasteSkip('当前站点已被单独禁用');
if (pasteMods.shift) return;
const rule = siteRule(HOST, cfg, editable, false);
if (!pasteMods.alt && !rule.upload) {
return pasteSkip('站点规则 ' + rule.reason + '(域名 ' + (HOST || '空') + ')');
}
const provider = activeProvider();
if (!provider) {
toast({ type: 'error', message: '没有可用的图床,请先在面板中配置' });
return;
}
if (!provider.uploadUrl) {
toast({ type: 'error', message: '当前图床未填写上传地址' });
return;
}
if (!files.some((f) => !validateFile(f, provider))) return pasteSkip('图片类型或体积不满足图床限制');
const sig = files.map((f) => [f.name || '', f.size || 0, f.type || ''].join('|')).join(';');
const now = Date.now();
if (sig && lastPaste.sig === sig && lastPaste.target === editable && now - lastPaste.at < 400) {
e.preventDefault();
e.stopPropagation();
if (e.stopImmediatePropagation) e.stopImmediatePropagation();
return;
}
lastPaste = { sig, at: now, target: editable };
e.preventDefault();
e.stopPropagation();
if (e.stopImmediatePropagation) e.stopImmediatePropagation();
console.info('[粘贴即传图] 开始上传 ' + files.length + ' 张图片(' + (provider.name || '') + ')');
handleImageFiles(files, editable);
}
/* =========================================================================
* 9. 启动
* ========================================================================= */
const INSTANCE_ATTR = 'data-piu-instance';
function existingInstance() {
try {
const root = document.documentElement;
const ver = root && root.getAttribute(INSTANCE_ATTR);
if (ver) return ver;
if (document.getElementById('piu-host')) return 'legacy';
} catch (e) { /* ignore */ }
return '';
}
const BOUND_DOCS = new WeakSet();
function bindDocument(doc) {
if (!doc || BOUND_DOCS.has(doc)) return;
BOUND_DOCS.add(doc);
doc.addEventListener('keydown', trackMods, true);
doc.addEventListener('paste', onPaste, true);
let frames = [];
try { frames = doc.querySelectorAll('iframe, frame'); } catch (e) { frames = []; }
for (const f of frames) {
try { bindDocument(f.contentDocument); } catch (e) { /* 跨域跳过 */ }
}
}
function watchNewFrames() {
document.addEventListener('load', (e) => {
const t = e.target;
if (!t || !/^i?frame$/i.test(String(t.tagName))) return;
try { bindDocument(t.contentDocument); } catch (err) { /* 跨域跳过 */ }
}, true);
// 焦点切入动态创建的 about:blank / srcdoc 富文本 iframe 时自动接管
window.addEventListener('blur', () => {
const el = document.activeElement;
if (el && /^i?frame$/i.test(String(el.tagName))) {
try { bindDocument(el.contentDocument); } catch (err) { /* 跨域跳过 */ }
}
});
}
function watchConfigSync() {
if (typeof GM_addValueChangeListener !== 'function') return;
try {
GM_addValueChangeListener(CONFIG_KEY, (_name, _oldVal, _newVal, remote) => {
if (!remote) return;
state.config = loadConfig();
if (state.shadow && !state.ui.panel.hidden) {
syncUIAfterConfigChange();
} else {
applyHistoryView();
applyFabVisibility();
}
});
} catch (e) { /* ignore */ }
}
function init() {
const dup = existingInstance();
if (dup) {
console.warn('[粘贴即传图] 本页已存在脚本实例(' + dup + '),当前实例 v' + VERSION +
' 已跳过。请检查是否重复安装了多个版本或多个管理器。');
return;
}
try { document.documentElement.setAttribute(INSTANCE_ATTR, VERSION); } catch (e) { /* ignore */ }
state.config = loadConfig();
bindDocument(document);
watchNewFrames();
watchConfigSync();
bindGlobalHotkeys();
if (IS_TOP) {
bindMenu();
applyFabVisibility(); // 非白名单站点不挂载任何 DOM
} else {
console.info('[粘贴即传图] 跨域子框架内运行,站点域名 ' + (HOST || '未知') + ',由本实例处理');
}
}
function bindMenu() {
if (typeof GM_registerMenuCommand !== 'function') return;
try {
GM_registerMenuCommand('打开面板', () => openPanel('history'));
GM_registerMenuCommand('图床设置', () => openPanel('providers'));
GM_registerMenuCommand('启用/禁用粘贴上传', () => {
state.config.enabled = !state.config.enabled;
saveConfig();
toast({ type: 'info', message: state.config.enabled ? '粘贴上传已启用' : '粘贴上传已禁用' });
});
GM_registerMenuCommand('当前站点启用/禁用', () => {
const next = !siteEnabled(HOST);
state.config.siteEnabled[HOST] = next;
saveConfig();
applyFabVisibility();
toast({ type: 'info', message: HOST + (next ? ' 已启用' : ' 已禁用') });
});
GM_registerMenuCommand('显示/隐藏右下角图标', () => {
state.config.showFab = state.config.showFab === false;
saveConfig();
applyFabVisibility();
toast({
type: 'info',
message: state.config.showFab
? '已显示悬浮图标'
: '已隐藏悬浮图标(可用 Alt+Shift+H 打开面板)',
});
});
} catch (e) { /* ignore */ }
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init, { once: true });
} else {
init();
}
})();