mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-05 03:59:27 +08:00
fix: 将首屏主题初始化脚本固定为静态文本
This commit is contained in:
@@ -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();//</script><script>themeInitAttack()</script>');
|
||||
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)();
|
||||
|
||||
|
||||
@@ -26,4 +26,5 @@ export function resolveTheme(preference: ThemePreference, systemDark: boolean):
|
||||
* 在 <head> 中内联执行的脚本:首屏绘制前读取本地缓存的偏好并设置 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){}})();`;
|
||||
|
||||
Reference in New Issue
Block a user