electron JavaScript -文档未定义(电子版)

zpgglvta  于 2022-12-08  发布在  Electron
关注(0)|答案(1)|浏览(195)

我想更改用户按下按钮时的背景颜色。
我有两个主要职能:darkTheme()用于暗模式,lightTheme()用于亮模式。

JavaScript语言

function changeAppearence() {
  let themeForPage = localStorage.getItem('theme');
  if (themeForPage === 'light'){
    lightTheme();
  } else if (themeForPage === 'dark'){
    darkTheme();
  } else {
    darkTheme();
  }
}

function darkTheme() {
  localStorage.setItem('theme', 'dark');

  document.getElementById('headerMainMenu').style.backgroundColor = '#212529';
  document.body.style.backgroundColor = '#343a40';
  document.body.style.color = 'white';

}

function lightTheme() {
  localStorage.setItem('theme', 'light');

  document.getElementById('headerMainMenu').style.backgroundColor = 'white';
  document.body.style.backgroundColor = 'white';
  document.body.style.color = 'white';

}

但在键入npm start命令后,我得到以下错误:

错误消息:

App threw an error during load
ReferenceError: document is not defined
    at darkTheme (/Users/user/Documents/#4_Website_ Development/Electron/electron-app/main.js:76:3)
    at changeAppearence (/Users/user/Documents/#4_Website_ Development/Electron/electron-app/main.js:15:5)
    at Object.<anonymous> (/Users/user/Documents/#4_Website_ Development/Electron/electron-app/main.js:8:1)
    at Module._compile (internal/modules/cjs/loader.js:1078:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1108:10)
    at Module.load (internal/modules/cjs/loader.js:935:32)
    at Module._load (internal/modules/cjs/loader.js:776:14)
    at Function.f._load (electron/js2c/asar_bundle.js:5:12913)
    at loadApplicationPackage (/Users/user/Documents/#4_Website_ Development/Electron/electron-app/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:110:16)
    at Object.<anonymous> (/Users/user/Documents/#4_Website_ Development/Electron/electron-app/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:222:9)

我还尝试在JavaScript文件中创建一个简单的document.body.style.color = 'white';,但没有任何函数,但我得到了同样的错误。

odopli94

odopli941#

你在哪里调用这些函数?看起来你试图从主进程调用它们,主进程在节点中运行,不能直接访问DOM。你可以使用ipcRendereripcMain沿着contextBridge在渲染器进程和主进程之间进行通信。但从上下文来看,这些函数是否应该在主进程中并不清楚。我最初的想法是,这些函数应该专门在渲染器进程中,因为这只影响渲染窗口,而不是应用程序全局。

相关问题