版本比较
网页个性渲染通用脚本
正文
增加 321 行删除 280 行
8 行未改动910111213141314151617181,870 行未改动全部展开18891890189118921893189318941895189618976 行未改动19041905190619071908190819091910191119121913191419151916191519161917191817 行未改动19361937193819391942194319401941194219431944194570 行未改动20162017201820192023202020212026202720282029203020312022202320242025202620272028202920302031203217 行未改动2050205120522053205720582059206020612062206320642065206620542055205620572058205920602061206220682069206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122072207320742113211421152076211621172118211921202121212220832084212321242125212620882089209021272128212921302093209421312132213321342135213621378 行未改动214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772 行未改动21802181218221832121212221232124212521842185218621872188212821292130218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112141221222132214221522162217221822192149222022212222222322242225222622272157222822292230223122322233223411 行未改动224622472248224921772250225122522253225414 行未改动2269227022712272220022012202220322732274227522764 行未改动2281228222832284221622172218221922852286228722882289229022912292229322212222222322242294229522962297229822992300230123022303230422262227222822292230223122322305230623072235223622372238223922402241224222432244224523082309231023112247224822492250225122522312231322542255225622572258231423152316231723182319232023212322232323242325232623272328232923302331233223332334226023352336226322642265226623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238454 行未改动24392440244124422335244324442445233924462447244824499 行未改动2459246024612462235723582359236023612362236323642365236623672368246324642465246624672468246924702471247224732474247524762477247824792480248124822377237823792380238123822383238423852386248324842485248624872488248924902491249224932494249524967 行未改动2504250525062507240225082404250925102511240725122409251325142515251625172518241525192520252124192522252325242423252525262527252845 行未改动257425752576257724772478247924802481248224832484248524862578257925802581258225832584258525862587258825892590249025912592259324942594259525962597259825002501250225032504250525062507250825092599260026012602260326042605260626072608260926102611261226132614261526162518251925202521252225232524252525262527261726182619262026212622262326242625262626272628262926302 行未改动26332634263526362538263725402638263926402543264125452642264325472548264425502551264526462554264726482649265026512652265325622654265526562566265726582659266026612662257226632664266526662667266826692580267026712672267310 行未改动26842685268626872599268826892690269126922605269326942695269640 行未改动2737273827392740265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268427412742274327442745269027462747274827492750269427512752275327547 行未改动2762276327642765271027662767276827699 行未改动27792780278127822728278327842785278627872734273527882789279027912740279227932794279530 行未改动28262827282828292779283028312832283378 行未改动291229132914291528662916286829172918291929206 行未改动29272928292929302883293129322886293329342935289029362937293829392940294129422898294329442945294688 行未改动303530363037303829953039304030413042299729982999304330443045304630473048304930503051305230533054305530093056305730583059306027 行未改动3088308930903091309230933094309530963097309830993100310162 行未改动31643165316631673168316931703171317224 行未改动31973198319932003201320232033204320523 行未改动32293230323132323233323432353236323730 行未改动32683269327032713272327332743275327632773278327932803281328232833284328532869 行未改动32963297329832993300330133023303330462 行未改动336733683369337033153371337233733374337533203376337733783379338033813382338333283384338533863387338831 行未改动34203421342234233368342434253426342734287 行未改动34363437343834393384344034413442344334445 行未改动345034513452345333983454345534003401345634573458345934603461346234073463346434653466346731 行未改动349935003501350234473503350435053506350766 行未改动357435753576357735223578357935803581358235833584358555 行未改动364136423643364435863645364636473648364945 行未改动3695369636973698364036993700370137023703142 行未改动全部展开3846384738483849379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817385038513852385338543855385638573826382738283829383038313832383338343858385938603861383938623841384238433844386338643865386638673868386938703871385438553872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438955 行未改动39013902390339043905390639073908390939103911391239133914391539163917391839193920392139228 行未改动8 行未改动## 一、软件简介
「网页渲染修改」是一款用户脚本(Tampermonkey 脚本),允许用户通过可视化界面修改网页中任意元素的背景样式,包括背景图片、视频、颜色、透明度、毛玻璃效果等,并支持刷新后持久化保存。
### # 使用效果(vjudge)### # 使用效果
## 二、安装与启动
### 安装要求1,870 行未改动全部展开// ==UserScript==// @name 网页渲染修改// @namespace http://tampermonkey.net/// @version 1.3// @description 网页渲染修改// @description 网页渲染修改 - IndexedDB 存储 + ZIP 导入导出// @author luogu fighting_man & Deepseek// @match *://*/*// @grant GM_addStyle// @grant GM_getValue6 行未改动
(function() { 'use strict';
console.log('🔍 ===== 网页渲染修改JS v1.3 (IndexedDB) 已加载 ====='); console.log('🔍 ===== 网页渲染修改JS v1.3 已加载 =====');
const PANEL_WIDTH_RATIO = 0.25; const HIGHLIGHT_CLASS = 'bg-magician-highlight'; const SELECTED_CLASS = 'bg-magician-selected'; const STORAGE_KEY = 'bg_magician_data'; const FULLPAGE_FLAG = '__fullpage_active__'; const MAX_RETRIES = 10; const RETRY_INTERVAL = 500;
let isPanelVisible = false; let activeElement = null; let highlightElement = null;17 行未改动 let realtimeTimeout = null; let fullPageStyleId = 'bg-magician-fullpage-style'; let fullPageBodyStyleId = 'bg-magician-fullpage-body'; let isFullPageActive = false;
// ===== 本地文件内存存储 ===== let localFiles = {}; let appliedElements = new WeakSet();
// ===== IndexedDB 存储 ===== const DB_NAME = 'bg_magician_db'; const STORE_NAME = 'bg_data';70 行未改动 let JSZipLoaded = false; let JSZipLoading = false; let JSZipCallbacks = [];
// ===== 使用 GM_xmlhttpRequest 加载 JSZip(绕过CSP) ===== function loadJSZip() { return new Promise((resolve, reject) => { // 检查是否已存在 if (typeof unsafeWindow.JSZip !== 'undefined') { JSZipLoaded = true; resolve(unsafeWindow.JSZip); return; } try { if (typeof unsafeWindow.JSZip !== 'undefined') { JSZipLoaded = true; resolve(unsafeWindow.JSZip); return; } } catch (e) {}
if (JSZipLoading) { JSZipCallbacks.push({ resolve, reject }); return;17 行未改动 }
console.log('⏳ 尝试加载 JSZip (CDN ' + (index + 1) + '):', cdnList[index]);
// 使用 GM_xmlhttpRequest 绕过 CSP GM_xmlhttpRequest({ method: 'GET', url: cdnList[index], onload: function(response) { try { // 在 unsafeWindow 上下文中执行代码 const scriptCode = response.responseText; const scriptFunc = new unsafeWindow.Function(scriptCode + '\nreturn JSZip;'); const JSZip = scriptFunc(); try { GM_xmlhttpRequest({ method: 'GET', url: cdnList[index], onload: function(response) { try { const wrapped = '(function(){' + response.responseText + '; return JSZip;})();'; const result = unsafeWindow.eval(wrapped);
if (typeof JSZip !== 'undefined') { unsafeWindow.JSZip = JSZip; if (result && typeof result === 'function') { unsafeWindow.JSZip = result; JSZipLoaded = true; JSZipLoading = false; console.log('✅ JSZip 加载成功'); resolve(result); for (const cb of JSZipCallbacks) { cb.resolve(result); } JSZipCallbacks = []; return; }
const fn = new unsafeWindow.Function(response.responseText + '\nreturn JSZip;'); const JSZip2 = fn(); if (JSZip2 && typeof JSZip2 === 'function') { unsafeWindow.JSZip = JSZip2; JSZipLoaded = true; JSZipLoading = false; console.log('✅ JSZip 加载成功'); resolve(JSZip2); for (const cb of JSZipCallbacks) { cb.resolve(JSZip2); } JSZipCallbacks = []; return; }
throw new Error('JSZip 未定义'); } catch (e) { console.warn('执行脚本失败,尝试下一个:', e); index++; tryLoad(); } }, onerror: function() { console.warn('加载失败,尝试下一个'); index++; tryLoad(); } }); } catch (e) { console.warn('GM_xmlhttpRequest 不可用,回退到 script 标签:', e); const script = document.createElement('script'); script.src = cdnList[index]; script.onload = function() { try { if (typeof unsafeWindow.JSZip !== 'undefined') { JSZipLoaded = true; JSZipLoading = false; console.log('✅ JSZip 加载成功 (GM_xmlhttpRequest)'); resolve(JSZip);
console.log('✅ JSZip 加载成功'); resolve(unsafeWindow.JSZip); for (const cb of JSZipCallbacks) { cb.resolve(JSZip); cb.resolve(unsafeWindow.JSZip); } JSZipCallbacks = []; } else { index++; tryLoad(); } } catch (e) { console.warn('执行脚本失败,尝试下一个:', e); } catch (err) { index++; tryLoad(); } }, onerror: function() { console.warn('加载失败,尝试下一个'); }; script.onerror = function() { index++; tryLoad(); } }); }; document.head.appendChild(script); } }
tryLoad(); });8 行未改动 b: parseInt(result[3], 16) } : { r: 255, g: 255, b: 255 }; }
function rgbToRgba(hex, alpha) { const { r, g, b } = hexToRgb(hex); if (alpha === 0) return 'transparent'; if (alpha === 1) return hex; return `rgba(${r}, ${g}, ${b}, ${alpha})`; }
function getPositionValue(pos) { if (typeof pos === 'number') return pos + '%'; return pos; }
function dataURLtoBlob(dataURL) { const arr = dataURL.split(','); const mime = arr[0].match(/:(.*?);/)[1]; const bstr = atob(arr[1]); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }
function dataUrlToBlobUrl(dataUrl) { try { const blob = dataURLtoBlob(dataUrl); return URL.createObjectURL(blob);2 行未改动 return dataUrl; } }
function rgbToRgba(hex, alpha) { const { r, g, b } = hexToRgb(hex); if (alpha === 0) return 'transparent'; if (alpha === 1) return hex; return `rgba(${r}, ${g}, ${b}, ${alpha})`; function isVideoFile(file) { const videoTypes = ['video/mp4', 'video/webm', 'video/ogg', 'video/quicktime', 'video/x-msvideo']; return videoTypes.includes(file.type) || /\.(mp4|webm|ogg|mov|avi|mkv)$/i.test(file.name); }
function getPositionValue(pos) { if (typeof pos === 'number') return pos + '%'; return pos; function isImageFile(file) { const imageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'image/webp', 'image/bmp']; return imageTypes.includes(file.type) || /\.(jpg|jpeg|png|gif|svg|webp|bmp)$/i.test(file.name); }
function fileToDataURL(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = function(e) { resolve(e.target.result); }; reader.onerror = function() { reject('读取文件失败'); }; reader.readAsDataURL(file); }); }
// ===== 选择器生成 ===== function getSelector(el) { if (!el) return null; if (el === document.body) return 'body';
if (el.id && el.id.trim() !== '') { return '#' + el.id; }
const dataAttrs = ['data-testid', 'data-id', 'data-key', 'data-name']; const dataAttrs = ['data-testid', 'data-id', 'data-key', 'data-name', 'data-component']; for (const attr of dataAttrs) { const val = el.getAttribute(attr); if (val) { return `[${attr}="${val}"]`; } }
let classSelector = ''; if (el.className && typeof el.className === 'string') { let classes = el.className.trim().split(/\s+/) .filter(c => c !== HIGHLIGHT_CLASS && c !== SELECTED_CLASS) .filter(c => c.length > 0 && !c.startsWith('bg-magician-')) .filter(c => !/^css-/.test(c)) .filter(c => !/^[a-z0-9]{8,}$/.test(c));
if (classes.length > 0) { classSelector = el.tagName.toLowerCase() + '.' + classes.join('.'); const tag = el.tagName.toLowerCase(); const mainClasses = classes.slice(0, 2).join('.'); return tag + '.' + mainClasses; } }
let path = [];11 行未改动 .filter(c => c.length > 0 && !c.startsWith('bg-magician-')) .filter(c => !/^css-/.test(c)) .filter(c => !/^[a-z0-9]{8,}$/.test(c)); if (classes.length > 0) { layerSelector = tag + '.' + classes.join('.'); layerSelector = tag + '.' + classes.slice(0, 2).join('.'); } }
if (parent) {14 行未改动 current = parent; maxDepth--; }
if (path.length === 1 && classSelector) { return classSelector; }
return 'body > ' + path.join(' > '); }
function findElements(selector) {4 行未改动 return []; } }
function isVideoFile(file) { const videoTypes = ['video/mp4', 'video/webm', 'video/ogg', 'video/quicktime', 'video/x-msvideo']; return videoTypes.includes(file.type) || /\.(mp4|webm|ogg|mov|avi|mkv)$/i.test(file.name); } function simplifySelector(selector) { const parts = selector.split(' > '); if (parts.length > 1) { const lastPart = parts[parts.length - 1]; if (lastPart && /^[a-z]+\.[a-zA-Z0-9_-]+/.test(lastPart)) { return lastPart; } }
function isImageFile(file) { const imageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'image/webp', 'image/bmp']; return imageTypes.includes(file.type) || /\.(jpg|jpeg|png|gif|svg|webp|bmp)$/i.test(file.name); } const classMatch = selector.match(/\.([a-zA-Z0-9_-]+)/g); const tagMatch = selector.match(/^([a-z]+)/i); if (classMatch && classMatch.length > 0) { const tag = tagMatch ? tagMatch[1] : '*'; const classes = classMatch.map(c => c.substring(1)); const mainClasses = classes.filter(c => !/^[a-z0-9]{6,}$/.test(c)).slice(0, 2); if (mainClasses.length > 0) { return tag + '.' + mainClasses.join('.'); } }
function fileToDataURL(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = function(e) { resolve(e.target.result); }; reader.onerror = function() { reject('读取文件失败'); }; reader.readAsDataURL(file); }); return null; }
function dataURLtoBlob(dataURL) { const arr = dataURL.split(','); const mime = arr[0].match(/:(.*?);/)[1]; const bstr = atob(arr[1]); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); } // ===== 动态渲染器(永不停止,跟进所有新元素) ===== function startDynamicRenderer() { console.log('🚀 启动动态渲染器');
// ===== 等待元素出现 ===== function restoreWithRetry(selector, params, retries = MAX_RETRIES) { if (retries <= 0) { console.warn('⚠️ 重试次数用尽,放弃恢复元素:', selector); return; } const processedElements = new WeakSet();
const elements = findElements(selector); if (elements.length > 0) { for (const el of elements) { console.log('✅ 找到元素,应用背景:', selector); render(el, params); function checkAndRender() { for (const [selector, params] of elementDataMap) { if (selector === 'body' && params.isFullPage) continue;
try { const elements = document.querySelectorAll(selector); for (const el of elements) { if (processedElements.has(el)) continue;
const hasBg = el.style.backgroundImage && el.style.backgroundImage !== 'none';
if (!hasBg) { render(el, params); processedElements.add(el); } else { processedElements.add(el); } } } catch (e) {} } return; }
console.log(`⏳ 等待元素出现 (${retries}次重试): ${selector}`); setTimeout(() => { restoreWithRetry(selector, params, retries - 1); }, RETRY_INTERVAL); checkAndRender();
const observer = new MutationObserver(() => { if (!window._renderPending) { window._renderPending = true; requestAnimationFrame(() => { window._renderPending = false; checkAndRender(); }); } });
observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['class', 'style', 'id'] });
setInterval(() => { if (!window._renderPending) { window._renderPending = true; requestAnimationFrame(() => { window._renderPending = false; checkAndRender(); }); } }, 500);
window._dynamicRenderer = { observer: observer, checkAndRender: checkAndRender, processedElements: processedElements };
console.log('✅ 动态渲染器已启动'); }
// ===== 核心:渲染 ===== function render(el, params) { if (!el) return;
appliedElements.add(el);
const selector = getSelector(el); let bgImage = params.bgImage || '';
if (bgImage === '__LOCAL_FILE__' && localFiles[selector]) {54 行未改动 // ===== 视频背景 ===== function createVideo(el, videoUrl, params) { removeVideo(el);
// 如果是 data: URL,转为 Blob URL let finalUrl = videoUrl; if (videoUrl && videoUrl.startsWith('data:video/')) { finalUrl = dataUrlToBlobUrl(videoUrl); console.log('🎬 data URL 已转为 Blob URL'); }
const { blur, opacity, color, positionX, positionY } = params; let bgColor;9 行未改动
const container = document.createElement('div'); container.className = 'bg-magician-video-container'; container.style.cssText = ` position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; z-index: -1; pointer-events: none; background-color: ${bgColor}; backdrop-filter: ${blur > 0 ? `blur(${blur}px)` : 'none'}; -webkit-backdrop-filter: ${blur > 0 ? `blur(${blur}px)` : 'none'}; `; position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; z-index: -1; pointer-events: none; background-color: ${bgColor}; backdrop-filter: ${blur > 0 ? `blur(${blur}px)` : 'none'}; -webkit-backdrop-filter: ${blur > 0 ? `blur(${blur}px)` : 'none'}; `;
const video = document.createElement('video'); video.src = finalUrl; video.autoplay = true; video.loop = true; video.muted = true; video.playsInline = true; video.style.cssText = ` position: absolute; top: 50%; left: 50%; min-width: 100%; min-height: 100%; width: auto; height: auto; transform: translate(-50%, -50%); object-fit: cover; `; position: absolute; top: 50%; left: 50%; min-width: 100%; min-height: 100%; width: auto; height: auto; transform: translate(-50%, -50%); object-fit: cover; `;
const posXMap = { left: '0%', center: '50%', right: '100%' }; const posYMap = { top: '0%', center: '50%', bottom: '100%' }; const finalPosX = posXMap[posX] || posX;7 行未改动 }
el.appendChild(container);
// 等待视频加载完成后播放 video.addEventListener('loadeddata', function() { video.play().catch(e => console.log('视频自动播放失败:', e)); video.play().catch(e => {}); });
// 如果视频已加载,立即播放 if (video.readyState >= 2) { video.play().catch(e => console.log('视频自动播放失败:', e)); video.play().catch(e => {}); }
return container; }
// ===== 移除视频背景 ===== function removeVideo(el) { const containers = el.querySelectorAll('.bg-magician-video-container'); for (const container of containers) { // 释放 video 的 src const video = container.querySelector('video'); if (video && video.src && video.src.startsWith('blob:')) { URL.revokeObjectURL(video.src); console.log('🗑️ 已释放 Blob URL'); } container.remove(); } }45 行未改动 bgImageStyle = 'background-image: none !important;'; }
bodyStyleTag.textContent = ` body { ${bgImageStyle} background-color: ${bgColor} !important; background-position: ${posX} ${posY} !important; background-size: cover !important; background-repeat: no-repeat !important; background-attachment: fixed !important; min-height: 100vh !important; } `; body { ${bgImageStyle} background-color: ${bgColor} !important; background-position: ${posX} ${posY} !important; background-size: cover !important; background-repeat: no-repeat !important; background-attachment: fixed !important; min-height: 100vh !important; } `; document.head.appendChild(bodyStyleTag);
if (bgImage && bgImage.trim() !== '' && finalIsVideo) { // 如果是 data: URL,转为 Blob URL let finalVideoUrl = bgImage; if (bgImage.startsWith('data:video/')) { finalVideoUrl = dataUrlToBlobUrl(bgImage); console.log('🎬 全网页 data URL 已转为 Blob URL'); }
const videoContainer = document.createElement('div'); videoContainer.className = 'bg-magician-fullpage-video'; videoContainer.style.cssText = ` position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; overflow: hidden; z-index: -1; pointer-events: none; background-color: ${bgColor}; `; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; overflow: hidden; z-index: -1; pointer-events: none; background-color: ${bgColor}; `;
const video = document.createElement('video'); video.src = finalVideoUrl; video.autoplay = true; video.loop = true; video.muted = true; video.playsInline = true; video.style.cssText = ` position: absolute; top: 50%; left: 50%; min-width: 100%; min-height: 100%; width: auto; height: auto; transform: translate(-50%, -50%); object-fit: cover; `; position: absolute; top: 50%; left: 50%; min-width: 100%; min-height: 100%; width: auto; height: auto; transform: translate(-50%, -50%); object-fit: cover; `;
const posXMap = { left: '0%', center: '50%', right: '100%' }; const posYMap = { top: '0%', center: '50%', bottom: '100%' }; const finalPosX = posXMap[posX] || posX;2 行未改动
videoContainer.appendChild(video); document.body.appendChild(videoContainer);
// 等待视频加载完成后播放 video.addEventListener('loadeddata', function() { video.play().catch(e => console.log('视频自动播放失败:', e)); video.play().catch(e => {}); });
// 如果视频已加载,立即播放 if (video.readyState >= 2) { video.play().catch(e => console.log('视频自动播放失败:', e)); video.play().catch(e => {}); }
console.log('✅ 全网页视频背景已创建'); }
console.log('✅ 全网页背景已应用'); }
// ===== 移除全网页背景 ===== function removeFullPage() { const style = document.getElementById(fullPageStyleId); if (style) style.remove(); const bodyStyle = document.getElementById(fullPageBodyStyleId); if (bodyStyle) bodyStyle.remove(); const videoContainer = document.querySelector('.bg-magician-fullpage-video'); if (videoContainer) { // 释放 video 的 src const video = videoContainer.querySelector('video'); if (video && video.src && video.src.startsWith('blob:')) { URL.revokeObjectURL(video.src); console.log('🗑️ 已释放 Blob URL'); } videoContainer.remove(); } appliedElements.delete(document.body); isFullPageActive = false; saveToStorage(); console.log('✅ 已移除全网页背景样式'); }
// ===== 保存数据 ===== function saveData(el, params) { if (!el) return;
const selector = getSelector(el); console.log('💾 保存数据,选择器:', selector);
const saveParams = { bgImage: params.bgImage || '', blur: params.blur || 0,10 行未改动 dataUrl: params.bgImage, isVideo: params.isVideo || false }; saveParams.bgImage = '__LOCAL_FILE__'; console.log('📁 本地文件已存入 IndexedDB:', selector); }
if (selector) { elementDataMap.set(selector, saveParams); saveToStorage(); console.log('✅ 数据已保存到 IndexedDB'); } else { console.warn('⚠️ 无法生成选择器,数据未保存'); } }40 行未改动 isVideo: hasVideo }; }
// ===== 应用存储的数据 ===== function applyStoredData() { console.log('🔄 应用存储的数据...');
if (isFullPageActive && elementDataMap.has('body')) { const bodyParams = elementDataMap.get('body'); if (bodyParams && bodyParams.isFullPage) { applyFullPage(bodyParams); } }
let applied = 0; for (const [selector, params] of elementDataMap) { if (selector === 'body' && params.isFullPage) continue;
const elements = findElements(selector); if (elements.length > 0) { for (const el of elements) { render(el, params); applied++; } } else { console.log(`⏳ 元素暂未出现: ${selector}`); restoreWithRetry(selector, params); } } if (applied > 0) { console.log(`✅ 已应用 ${applied} 个元素的背景`); } }
// ===== 还原元素 ===== function resetElement(el) { if (!el) return;
const selector = getSelector(el); console.log('🔄 还原元素:', selector || el.tagName);
appliedElements.delete(el);
if (localFiles[selector]) { delete localFiles[selector]; console.log('📁 已清除本地文件:', selector); }
if (selector === 'body' && isFullPageActive) { removeFullPage();7 行未改动 } removeVideo(document.body); elementDataMap.delete('body'); saveToStorage(); console.log('✅ 已还原全网页背景'); return; }
if (selector) {9 行未改动 for (const style of stylesToRemove) { el.style.removeProperty(style); }
// 移除视频并释放 Blob URL removeVideo(el);
if (el.getAttribute('style') === '') { el.removeAttribute('style'); }
console.log('✅ 已还原单元素背景'); }
// ===== 导出 ZIP ===== function exportData() { console.log('📦 开始导出数据...'); loadJSZip().then(function(JSZip) { try { const data = {}; data[FULLPAGE_FLAG] = isFullPageActive;30 行未改动 document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(url), 3000); console.log('✅ ZIP 导出成功');
const statusEl = document.getElementById('bg-import-status'); if (statusEl) { statusEl.textContent = '✅ 导出成功!';78 行未改动 newLocalFiles[selector] = { dataUrl: dataUrl, isVideo: dataUrl.startsWith('data:video/') }; console.log('✅ 已加载媒体文件:', filename); } else { console.warn('⚠️ 未找到媒体文件:', filename); params.bgImage = ''; } } }6 行未改动 if (!elementDataMap.has(key)) { elementDataMap.set(key, value); } } console.log('✅ 已追加数据'); } else { elementDataMap = newMap; console.log('✅ 已覆盖数据'); } } else { elementDataMap = newMap; console.log('✅ 已导入数据'); }
if (data[FULLPAGE_FLAG] !== undefined) { isFullPageActive = data[FULLPAGE_FLAG]; }
saveToStorage(); console.log('✅ 数据导入成功,共', elementDataMap.size, '条'); resolve(elementDataMap.size); } catch (err) { reject('导入失败: ' + err.message); }88 行未改动 // ===== SPA路由变化检测 ===== function checkUrlChange() { const currentUrl = window.location.href; if (currentUrl !== lastUrl) { console.log('🔄 检测到URL变化:', currentUrl); lastUrl = currentUrl;
if (window._dynamicRenderer) { window._dynamicRenderer.processedElements = new WeakSet(); setTimeout(() => { applyStoredData(); }, 500); setTimeout(() => { window._dynamicRenderer.checkAndRender(); }, 200); } } }
// ===== UI ===== function createFloatingBall() { if (floatingBall) return; floatingBall = document.createElement('div'); floatingBall.id = 'bg-magician-ball'; floatingBall.textContent = '🎨'; floatingBall.title = '打开网页渲染修改JS'; floatingBall.title = '打开网页渲染修改'; document.body.appendChild(floatingBall); floatingBall.addEventListener('click', function(e) { e.stopPropagation(); showPanel();27 行未改动 cursor: pointer; z-index: 2147483647; user-select: none; border: 1px solid #666; border-radius: 50%; box-shadow: 0 2px 12px rgba(0,0,0,0.3); } #bg-magician-ball:hover { background: #5a5a7a; transform: scale(1.05); } #bg-magician-panel { position: fixed; top: 0;62 行未改动 border: 1px solid #555; color: #ddd; box-sizing: border-box; font-size: 13px; border-radius: 4px; } #bg-magician-panel input[type="range"] { width: 100%; margin: 4px 0;24 行未改动 cursor: pointer; border: 1px solid #666; color: white; min-width: 60px; border-radius: 4px; } #bg-magician-panel .save-btn { background: #4a4a6a; }23 行未改动 background: #3a3a3a; border: 1px solid #555; color: #ddd; font-size: 13px; border-radius: 4px; } #bg-magician-panel .hint-text { text-align: center; margin-top: 8px;30 行未改动 border: 1px solid #555; color: #ddd; box-sizing: border-box; font-size: 13px; border-radius: 4px; } #bg-magician-panel .fp-section .fp-row button { padding: 6px 16px; background: #2a5a4a; color: white; border: 1px solid #666; font-size: 13px; cursor: pointer; white-space: nowrap; border-radius: 4px; } #bg-magician-panel .fp-section .fp-row button:hover { background: #3a6a5a; }9 行未改动 margin-top: 6px; text-align: center; cursor: pointer; transition: border-color 0.3s; border-radius: 4px; } #bg-magician-panel .file-upload-area:hover { border-color: #888; }62 行未改动 panelElement = document.createElement('div'); panelElement.id = 'bg-magician-panel'; panelElement.innerHTML = ` <div class="panel-header"> <h2>网页渲染修改JS <span style="font-size:11px;color:#666;">v1.3</span></h2> <h2>网页渲染修改 <span style="font-size:11px;color:#666;">v1.3</span></h2> <button class="panel-close" id="bg-panel-close">✕</button> </div> <div id="bg-panel-content"> <div class="param-group"> <label>背景媒体 URL <span style="color:#888;font-weight:normal;">(图片或视频)</span></label> <label>背景媒体 URL</label> <input type="text" id="bg-image-input" placeholder="输入图片URL 或 视频URL" /> <div style="font-size:10px;color:#666;margin-top:3px;"> 支持: 图片 (jpg/png/gif/svg/webp) 或 视频 (mp4/webm/ogg/mov) </div> </div>
<div class="param-group"> <label>或选择本地文件 <span style="color:#888;font-weight:normal;">(IndexedDB存储,刷新保留)</span></label> <label>或选择本地文件</label> <div class="file-upload-area" id="local-file-area"> <span class="file-label">📁 点击选择本地图片或视频</span> <input type="file" id="local-file-input" accept="image/*,video/*" /> <div class="file-name" id="local-file-name"></div>31 行未改动 <div class="range-labels"><span>0</span><span>30</span></div> <span class="range-value" id="bg-blur-value">0 px</span> </div> <div class="param-group"> <label>背景透明度 <span style="color:#888;font-weight:normal;">(仅背景)</span></label> <label>背景透明度</label> <input type="range" id="bg-opacity-range" min="0" max="1" step="0.05" value="1" /> <div class="range-labels"><span>0 (透明)</span><span>1 (不透明)</span></div> <span class="range-value" id="bg-opacity-value">1.00</span> </div>7 行未改动 <button class="reset-btn" id="bg-reset-btn">↩️ 还原当前元素</button> </div>
<div class="fp-section"> <span class="fp-label">🌐 全网页背景(底层)</span> <span class="fp-label">🌐 全网页背景</span> <div class="fp-row"> <input type="text" id="fp-url-input" placeholder="输入图片或视频URL" /> <button id="fp-apply-btn">应用</button> </div>5 行未改动 <div class="fp-status" id="fp-status-text">输入媒体URL或选择本地文件,点击应用为全网页背景</div> </div>
<div class="fp-section"> <span class="fp-label" style="color:#4a9eff;">📦 数据管理 (IndexedDB)</span> <span class="fp-label" style="color:#4a9eff;">📦 数据管理</span> <div class="fp-row"> <button id="bg-export-btn" style="flex:1;background:#3a5a4a;color:white;border:1px solid #666;padding:6px 12px;cursor:pointer;font-size:13px;">⬇️ 导出ZIP</button> <button id="bg-import-btn" style="flex:1;background:#3a4a6a;color:white;border:1px solid #666;padding:6px 12px;cursor:pointer;font-size:13px;">⬆️ 导入ZIP</button> <button id="bg-export-btn" style="flex:1;background:#3a5a4a;color:white;border:1px solid #666;padding:6px 12px;cursor:pointer;font-size:13px;border-radius:4px;">⬇️ 导出ZIP</button> <button id="bg-import-btn" style="flex:1;background:#3a4a6a;color:white;border:1px solid #666;padding:6px 12px;cursor:pointer;font-size:13px;border-radius:4px;">⬆️ 导入ZIP</button> </div> <input type="file" id="bg-import-file" accept=".zip" style="display:none;" /> <div class="fp-status" id="bg-import-status" style="margin-top:4px;font-size:11px;color:#888;">导出ZIP包,或导入ZIP备份恢复</div> </div>
<div class="status-text" id="bg-status-text">💡 v1.3: IndexedDB存储,本地文件刷新保留</div> <div class="status-text" id="bg-status-text">💡 新元素出现时自动渲染</div> </div> `; document.body.appendChild(panelElement);
31 行未改动 render(activeElement, tempParams); } document.getElementById('bg-status-text').textContent = '✅ 本地文件已加载: ' + file.name; setTimeout(() => { document.getElementById('bg-status-text').textContent = '💡 v1.3: IndexedDB存储,本地文件刷新保留'; document.getElementById('bg-status-text').textContent = '💡 新元素出现时自动渲染'; }, 2000); } catch (err) { alert('加载文件失败: ' + err); }66 行未改动 try { const count = await importZip(file); document.getElementById('bg-import-status').textContent = `✅ 成功导入 ${count} 条数据,刷新页面生效`; document.getElementById('bg-import-status').style.color = '#4a9eff'; applyStoredData(); if (window._dynamicRenderer) { window._dynamicRenderer.processedElements = new WeakSet(); window._dynamicRenderer.checkAndRender(); } setTimeout(() => { document.getElementById('bg-import-status').textContent = '导出ZIP包,或导入ZIP备份恢复'; document.getElementById('bg-import-status').style.color = '#888'; }, 5000);55 行未改动 saveData(activeElement, tempParams); render(activeElement, tempParams); document.getElementById('bg-status-text').textContent = '✅ 已保存到 IndexedDB!'; setTimeout(() => { document.getElementById('bg-status-text').textContent = '💡 v1.3: IndexedDB存储,本地文件刷新保留'; document.getElementById('bg-status-text').textContent = '💡 新元素出现时自动渲染'; }, 2000); } else { alert('请先点击选择一个背景元素'); }45 行未改动 document.getElementById('bg-status-text').textContent = '🚫 已取消全网页背景'; clearSelected(); clearHighlights(); setTimeout(() => { document.getElementById('bg-status-text').textContent = '💡 v1.3: IndexedDB存储,本地文件刷新保留'; document.getElementById('bg-status-text').textContent = '💡 新元素出现时自动渲染'; }, 2000); } } else { alert('当前没有全网页背景');142 行未改动全部展开 saveToStorage(); } }
// ===== DOM变化监听 ===== function setupMutationObserver() { const observer = new MutationObserver(function(mutations) { for (const [selector, params] of elementDataMap) { if (selector === 'body' && params.isFullPage) continue; const elements = findElements(selector); if (elements.length > 0) { for (const el of elements) { const computed = getComputedStyle(el); const bgImage = computed.backgroundImage; if (params.bgImage && params.bgImage.trim() !== '' && (bgImage === 'none' || bgImage === '')) { console.log('🔄 DOM变化检测到元素,重新渲染:', selector); render(el, params); } } } } });
observer.observe(document.body, { childList: true, subtree: true }); return observer; }
// ===== 初始化 ===== if (document.readyState === 'complete') { init(); } else { window.addEventListener('load', init); }
async function init() { console.log('📦 初始化...');
// 预加载 JSZip(不阻塞初始化) loadJSZip().then(function() { console.log('✅ JSZip 已预加载'); }).catch(function(e) { console.warn('⚠️ JSZip 预加载失败:', e); });
await loadFromStorage(); cleanupOldData(); createPanel(); createFloatingBall(); applyStoredData();
domObserver = setupMutationObserver();
setInterval(checkUrlChange, 500);
if (panelElement) { panelElement.classList.remove('visible'); isPanelVisible = false; } if (floatingBall) { floatingBall.style.display = 'flex'; } document.body.style.marginRight = '0';
console.log('✅ 网页渲染修改JS v1.3 初始化完成!'); console.log('💡 IndexedDB存储,本地文件刷新后自动恢复'); loadJSZip().then(function() { console.log('✅ JSZip 已预加载'); }).catch(function(e) { console.warn('⚠️ JSZip 预加载失败:', e); });
if (isFullPageActive && elementDataMap.has('body')) { const bodyParams = elementDataMap.get('body'); if (bodyParams && bodyParams.isFullPage) { console.log('🌐 立即应用全网页背景'); applyFullPage(bodyParams); } }
// 再启动动态渲染器(处理其他元素) startDynamicRenderer();
setInterval(checkUrlChange, 500);
console.log('✅ 网页渲染修改JS v1.3 初始化完成'); }
document.addEventListener('keydown', function(e) { if (e.ctrlKey && e.altKey && e.key === 'p') {5 行未改动 hidePanel(); } });
// ===== 暴露全局接口 ===== window.bgMagician = { showPanel: showPanel, hidePanel: hidePanel, data: elementDataMap, resetElement: resetElement, removeFullPage: removeFullPage, isFullPageActive: () => isFullPageActive, exportData: exportData, importZip: importZip, render: render, saveToStorage: saveToStorage, getSelector: getSelector, findElements: findElements, clearAll: function() { elementDataMap.clear(); localFiles = {}; removeFullPage();8 行未改动