Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
how to use webContents.send function of electron.js in other ipc render file?

I am trying to separate the IPC function from the main.js file in electron because it gets too long

how can I use this webContents.send in different js file not in main.js

 mainWindow.webContents.send("search",recordset.recordset)

it shows this error Cannot read properties of undefined (reading 'webContents')

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Separation of concerns will be your number one priority here. To achieve this, you can use setters and getters.

Remember, when Node first require's a module, it is also cached. Let's use this advantage as a form of state management.


Prior to separating / refactoring your code, you will find that your main.js file can grow to an enormous size. Using techniques such as this will allow you to split up your code into easily manageable, readable, single responsibility segments of code.

If you haven’t done so already, let's move construction of your mainWindow out of the main.js file and into its own file.

main.js (main thread)

// Import the necessary Electron modules.
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;

// Import the necessary Node modules.
const nodePath = require('path');

// Import the necessary Application modules.
const appMainWindow = require(nodePath.join(__dirname, 'main-window'));

// Prevent garbage collection.
let mainWindow = null;

// Application is now ready to start.
electronApp.on('ready', () => {
    mainWindow = appMainWindow.create();
});

// Re-activate Application when in macOS dock.
electronApp.on('activate', () => {
    if (electronBrowserWindow.getAllWindows().length === 0) {
        appMainWindow.create(mainWindow);
    }
});

// Close Application completely if not on macOS.
electronApp.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        electronApp.quit();
    }
});

Having management of the mainWindow object in its own file separates our code into more readable and manageable chunks.

main-window.js (main thread)

// Import the necessary Electron modules.
const electronBrowserWindow = require('electron').BrowserWindow;

// Define the main window.
let mainWindow;

// Create the main window.
function create() {
    mainWindow = new electronBrowserWindow({
        x: 0,
        y: 0,
        width: 800,
        height: 600,
        show: false,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: nodePath.join(__dirname, 'preload.js')
        }
    });

    // Load the main window.
    mainWindow.loadFile(nodePath.join(__dirname, 'main-window.html'))
        .then(() => { mainWindow.show(); })
        
    return mainWindow;
}

// Get the main window object.
function get() {
    return mainWindow;
}

// Export the publicly available functions.
module.exports = {create, get};

Finally, in your file (or any other file) that requires reference to your mainWindow object, just require your main-window.js file and call the get() function.

any-file (main thread)

// Import the necessary Node modules.
const nodePath = require('path');

// Import the necessary Application modules.
const appMainWindow = require(nodePath.join(__dirname, 'main-window'));

// Lets use it.
appMainWindow.get().webContents.send("search", recordset.recordset);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda