使用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>

View File

@@ -35,6 +35,19 @@ const Home = () => {
}
setHomePageContent(content);
localStorage.setItem('home_page_content', content);
// 如果内容是 URL则发送主题模式
if (data.startsWith('https://')) {
const iframe = document.querySelector('iframe');
if (iframe) {
const theme = localStorage.getItem('theme-mode') || 'light';
// 测试是否正确传递theme-mode给iframe
// console.log('Sending theme-mode to iframe:', theme);
iframe.onload = () => {
iframe.contentWindow.postMessage({ themeMode: theme }, '*');
};
}
}
} else {
showError(message);
setHomePageContent('加载首页内容失败...');