electron中,自定义custom.js通过引用调用main.js中的变量
electron中,自定义custom.js通过引用调用main.js中的变量在 Electron 中, `custom.js`直接访问`main.js`中的变量并不直接可行,因为它们运行在不同的上下文中(主进程和渲染进程)。但是,你可以通过将变量放入`global`对象中,或者通过使用 IPC(进程间通信)来实现这一点。
### 方法 1:使用`global`对象
你可以在`main.js`中将变量放入`global`对象中,然后在`custom.js`中访问它。
#### 1. 在`main.js`中定义变量并放入`global`对象
const { app, BrowserWindow } = require('electron');
const customModule = require('./js/custom.js'); // 导入自定义 JS 文件
global.myVariable = "Hello from main.js"; // 将变量放入 global 对象
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, 'preload.js') // 使用 preload.js 进行安全通信
}
});
win.loadFile('index.html');
// 调用自定义模块中的函数
console.log(customModule.greet(global.myVariable)); // 输出: Hello from main.js!
}
app.whenReady().then(createWindow);
#### 2. 在`custom.js`中使用`global`对象
// js/custom.js
function greet() {
return `Hello, ${global.myVariable}!`; // 直接使用 global 对象中的变量
}
function add(a, b) {
return a + b;
}
// 导出函数
module.exports = { greet, add };
### 方法 2:使用 IPC(进程间通信)
如果你想要更安全和更灵活的方式,可以使用 IPC 来在主进程和渲染进程之间传递数据。
#### 1. 在`main.js`中设置 IPC
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
let myVariable = "Hello from main.js"; // 定义一个变量
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, 'preload.js') // 使用 preload.js 进行安全通信
}
});
win.loadFile('index.html');
// 监听请求
ipcMain.handle('get-variable', () => {
return myVariable; // 返回变量的值
});
}
app.whenReady().then(createWindow);
#### 2. 在`preload.js`中暴露 IPC
// preload.js
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('myAPI', {
getVariable: () => ipcRenderer.invoke('get-variable') // 通过 IPC 获取变量
});
#### 3. 在渲染进程中调用
html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Electron App</title>
</head>
<body>
<script>
window.myAPI.getVariable().then(variable => {
console.log(variable); // 输出: Hello from main.js!
});
</script>
</body>
</html>
### 总结
- **方法 1** 使用`global`对象,可以直接在`custom.js`中访问`main.js`中的变量。
- **方法 2** 使用 IPC,可以在主进程和渲染进程之间安全地传递数据,适合更复杂的应用场景。
页:
[1]