|  | 
 
| electron中在custom.js中调用main.js中的方法函数 要在  `custom.js`  中调用  `main.js`  中的方法或函数,可以通过将这些方法作为参数传递给  `custom.js`  中的函数。这样可以保持模块之间的分离,同时允许  `custom.js`  调用  `main.js`  中的功能。
 以下是一个改进的示例,展示如何在  `custom.js`  中调用  `main.js`  中的方法。
 ### 1. 在  `main.js`  中定义方法并传递给  `custom.js`
 **main.js**
 
 复制代码const { app, BrowserWindow } = require('electron');
const customModule = require('./js/custom.js'); // 导入自定义 JS 文件
 // 定义一个方法
function greet(name) {
    return `Hello, ${name}!`;
}
 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');
     // 将方法传递给 custom.js
    customModule.callGreet(greet, 'World'); // 调用 custom.js 中的函数并传递 greet 方法
}
 app.whenReady().then(createWindow);
 ### 2. 在  `custom.js`  中调用  `main.js`  的方法
 **js/custom.js**
 
 复制代码// custom.js
function callGreet(greetFunction, name) {
    const message = greetFunction(name); // 调用传递的函数
    console.log(message); // 输出: Hello, World!
}
 // 导出函数
module.exports = { callGreet };
 ### 3. 启动应用
 确保你的项目结构正确,然后运行 Electron 应用。你应该能在控制台看到  `Hello, World!`  的输出。
 ### 总结
 - 在  `main.js`  中定义一个方法(如  `greet` ),并在创建窗口时将其作为参数传递给  `custom.js`  中的函数。
 - 在  `custom.js`  中,接受这个方法并调用它,传递所需的参数。
 - 这种方式允许你在自定义模块中灵活地使用主进程中的方法,同时保持代码的清晰和模块化。
 
 
 | 
 |