简体   繁体   English

Electron:在与 index.js 不同的 javascript 中调用函数

[英]Electron: Call a function in a different javascript from index.js

I want to call a function in second_script.js when the window is in focus, which is detected from my main.js (index.js) file.当窗口处于焦点时,我想在second_script.js调用一个函数,这是从我的main.js (index.js) 文件中检测到的。 The second_script.js is used within a different HTML file as well. second_script.js也用于不同的 HTML 文件中。

main.js主文件

  win = new BrowserWindow({
    width: 1000,
    height: 600,
    resizable: false,
    frame: true
  })

  win.on('focus', function () {
    call_that_function();
  });

second_script.js second_script.js

This is located in scripts/second_script.js and used in a different HTML file.它位于scripts/second_script.js并在不同的 HTML 文件中使用。

function call_that_function() {
    //code
}

How do I bridge this gap such that the main.js will call that function whenever my window is in focus?我如何弥合这个差距,以便 main.js 每当我的窗口处于焦点时都会调用该函数?

Electron is based on node.js . Electron 基于node.js

Export that function in your second_script.js and then import/require it and call it inside your main.js .在您的second_script.js导出该函数,然后导入/要求它并在您的main.js调用它。

Another way to communicate inside Electron is using the ipcMain :在 Electron 内部进行通信的另一种方式是使用ipcMain

const { ipcMain } = require('electron');

Spy on messages like below inside your second_script.js :在你的second_script.js如下消息:

ipcMain.on('CHANNEL_NAME', (event, arg) => {
  console.log('message received', event, args);
  // call your func here
);

Send messages like below inside your main.js :main.js发送如下消息:

win.on('focus', function () {
  ipcRenderer.send('CHANNEL_NAME', 'ping');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM