From 8e71ab2a50210da9e6777b60f298f914ab39e8bb Mon Sep 17 00:00:00 2001 From: margrop <1731827+margrop@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:22:07 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=B0=86=E9=A6=96=E5=B1=8F=E4=B8=BB?= =?UTF-8?q?=E9=A2=98=E5=88=9D=E5=A7=8B=E5=8C=96=E8=84=9A=E6=9C=AC=E5=9B=BA?= =?UTF-8?q?=E5=AE=9A=E4=B8=BA=E9=9D=99=E6=80=81=E6=96=87=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/__tests__/unit/theme.test.tsx | 11 +++++++++++ src/lib/theme.ts | 3 ++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/__tests__/unit/theme.test.tsx b/src/__tests__/unit/theme.test.tsx index 7e6c6bf4..eba399f7 100644 --- a/src/__tests__/unit/theme.test.tsx +++ b/src/__tests__/unit/theme.test.tsx @@ -100,6 +100,17 @@ describe('主题工具函数', () => { expect(resolveTheme('dark', false)).toBe('dark'); }); + it('本地缓存中的代码片段不会作为首屏脚本执行', () => { + const injected = vi.fn(); + vi.stubGlobal('themeInitAttack', injected); + localStorage.setItem(THEME_STORAGE_KEY, 'dark");themeInitAttack();//'); + systemDark = true; + new Function(THEME_INIT_SCRIPT)(); + expect(injected).not.toHaveBeenCalled(); + expect(htmlIsDark()).toBe(true); + expect(document.documentElement.style.colorScheme).toBe('dark'); + }); + it('首屏脚本按本地缓存的偏好设置 dark 类,没有缓存时跟随系统', () => { const run = () => new Function(THEME_INIT_SCRIPT)(); diff --git a/src/lib/theme.ts b/src/lib/theme.ts index c90ddc74..239c9022 100644 --- a/src/lib/theme.ts +++ b/src/lib/theme.ts @@ -26,4 +26,5 @@ export function resolveTheme(preference: ThemePreference, systemDark: boolean): * 在 中内联执行的脚本:首屏绘制前读取本地缓存的偏好并设置 html 的 dark 类, * 读取失败(如隐私模式禁用存储)时按系统设置处理 */ -export const THEME_INIT_SCRIPT = `(function(){try{var p=null;try{p=localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)})}catch(e){}var d=p==="dark"||(p!=="light"&&window.matchMedia("(prefers-color-scheme: dark)").matches);var r=document.documentElement;r.classList.toggle("dark",d);r.style.colorScheme=d?"dark":"light"}catch(e){}})();`; +// 首屏脚本保持静态文本,不向可执行代码中插入序列化值;缓存键的一致性由执行测试验证。 +export const THEME_INIT_SCRIPT = `(function(){try{var p=null;try{p=localStorage.getItem("app-theme")}catch(e){}var d=p==="dark"||(p!=="light"&&window.matchMedia("(prefers-color-scheme: dark)").matches);var r=document.documentElement;r.classList.toggle("dark",d);r.style.colorScheme=d?"dark":"light"}catch(e){}})();`;