How to pass parameters from main process to render processes in Electron

前端 未结 7 985
隐瞒了意图╮
隐瞒了意图╮ 2021-02-13 02:30

I have an Electron app that can open different windows.

On app launch the app open a set of window(s) (that load the same HTML and JS files) but with params to change ea

7条回答
  •  耶瑟儿~
    2021-02-13 02:34

    A few methods:

    loadURL Query String

    The query string method others have posted seems to work fine. It might even be the easiest.

    additionalArguments

    Electron's documentation says additionalArguments is:

    Useful for passing small bits of data down to renderer process preload scripts.

    Main

    const win = new BrowserWindow({
      width: 800,
      height: 600,
      backgroundColor: '#000000'
      webPreferences: {
        additionalArguments: ["myvarvalue", "secondvarvalue", "--another=something"]
      }
    });
    

    Renderer

    window.process.argv is going to look something like:

    ["--num-raster-threads=2",
    "--enable-gpu-memory-buffer-compositor-resources",
    "--enable-gpu-async-worker-context",
    ...
    "--renderer-client-id=4",
    "myvarvalue",
    "secondvarvalue",
    "--another=something"]
    

    It will append an array of strings. You could do something window.process.argv.slice(-3) to grab the last items in the array.


    IPC Main / Render

    Like you said, it seems complicated for what you are trying to do, but maybe this helps:

    Main

    const { ipcMain } = require('electron');
    
    var mainProcessVars = {
      somevar: "name",
      anothervar: 33
    }
    
    ipcMain.on('variable-request', function (event, arg) {
      event.sender.send('variable-reply', [mainProcessVars[arg[0]], mainProcessVars[arg[1]]]);
    });
    

    Renderer

    const { ipcRenderer } = electron;
    
    electron.ipcRenderer.send('variable-request', ['somevar', 'anothervar']);
    
    ipcRenderer.on('variable-reply', function (event, args) {
      console.log(args[0]); // "name"
      console.log(args[1]); // 33
    });
    

    This way allows you to send data besides strings.

提交回复
热议问题