How to call a function/module in Electron from my webpage?

前端 未结 1 1137
抹茶落季
抹茶落季 2021-02-05 17:16

I\'ll try to describe a minimized question in short paragraphs.

In short, I want to use some logic or call some functions in my Electron App from the webpage that is

相关标签:
1条回答
  • 2021-02-05 18:10

    There are two main ways to communicate between the renderer process and the main process.

    1. One way would be to use the remote module to require the code you want to take from the main process. This object will contain anything you export from your main process code.

    // main process, for example app/main.js
    exports.test = () => console.log('Yay');
    
    // renderer process, for example app/renderer.js
    const { remote } = require('electron');
    const mainProcess = remote.require('./main.js');
    
    mainProcess.test(); // 'Yay'
    

    2. Another way would be to use Inter Process Communication to send/receive events between the main process and the renderer process:

    // main process, for example app/main.js
    myWindow.webContents.send('my-cool-log-event', 'Yay');
    
    // renderer process, for example app/renderer.js
    const { ipcRenderer } = require('electron');
    ipcRenderer.on('my-cool-log-event', (evt, msg) => console.log(msg)); // 'Yay'
    

    If you want to call a function from the main process when a click event fires in a renderer process, you can use either approach.

    1.

    // main process, for example app/main.js
    exports.onClick = () => console.log('Yay');
    
    // renderer process, for example app/renderer.js
    const { remote } = require('electron');
    const mainProcess = remote.require('./main.js');
    
    document
      .querySelector('#elem')
      .addEventListener('click', () => {
        mainProcess.onClick();
      });
    

    2.

    // main process, for example app/main.js
    const { ipcMain } = require('electron')
    ipcMain.on('click', () => console.log('do something'));
    
    // renderer process, for example app/renderer.js
    const { ipcRenderer } = require('electron');
    
    document
      .querySelector('#elem')
      .addEventListener('click', () => {
        ipcRenderer.send('click');
      });
    
    0 讨论(0)
提交回复
热议问题