使用postMessage向iframe传参theme-mode,实现切换子页面主题的功能

子页面的js示例
```
<script>
    // 接收父页面的主题模式
    window.addEventListener('message', function(event) {
        if (event.data.themeMode) {
            var theme = event.data.themeMode;
            // 测试是否正确接受到theme-mode的值
            // console.log('Received theme mode from parent:', theme);
            applyTheme(theme);
        }
    });

    // 定义一个函数来应用主题
    function applyTheme(theme) {
        var body = document.body;
        if (theme === 'dark') {
            body.classList.add("dark-mode");
            document.getElementById("darkModeToggle").checked = true;
        } else {
            body.classList.remove("dark-mode");
            document.getElementById("darkModeToggle").checked = false;
        }
    }
</script>
```
This commit is contained in:
GuoRuqiang
2024-09-22 14:09:03 +00:00
parent edce1f7046
commit 574d7a0914
2 changed files with 21 additions and 2 deletions

View File

@@ -118,13 +118,19 @@ const HeaderBar = () => {
useEffect(() => {
if (theme === 'dark') {
document.body.setAttribute('theme-mode', 'dark');
} else {
document.body.removeAttribute('theme-mode');
}
// 发送当前主题模式给子页面
const iframe = document.querySelector('iframe');
if (iframe) {
iframe.contentWindow.postMessage({ themeMode: theme }, '*');
}
if (isNewYear) {
console.log('Happy New Year!');
}
}, []);
}, [theme]); // 监听 theme-mode 的变化
return (
<>
<Layout>