skip to Main Content

When I click on a menu item I get an error:

A JavaScript error occurred in the main process

How can I fix this?

Code:

Main.js

const { Menu } = require('electron')
const { createNewFile } = require('./js/createNewFile.js')

const menu = [
{
    label: 'File',
    submenu: [
    {
        label: 'New',
        click: () => {
            createNewFile()
        },
    }
}];

createNewFile.js

function createNewFile() {
    document.getElementById('newFileWindow').classList.remove('hiddenFileWindow')
}
module.exports = createNewFile

When using console.log(...) nothing works in the function either.

Could it be because I have a node_modules folder that is not read-only?

2

Answers


  1. You are missing a step, the main process doesn’t have access to your renderer process‘s DOM. If you want to change something in the DOM from the menu, you need to use IPC and a preload file to communicate between your processes. For example:

    renderer.js

    window.electronAPI.createNewFile(() => {
     document.getElementById('newFileWindow').classList.remove('hiddenFileWindow');
    });
    

    preload.js

    const { contextBridge, ipcRenderer } = require('electron');
    
    contextBridge.exposeInMainWorld('electronAPI', {
      createNewFile: (callback) => ipcRenderer.on('newFileWindow', callback)
    });
    

    main.js

    const menu = [{
      label: 'File',
      submenu: [
        {
          label: 'New',
          // `mainWindow` is the window you created with `new BrowserWindow()`
          click: () => mainWindow.webContents.send('createNewFile')
        }
    }];
    
    Login or Signup to reply.
  2. Did you block security precautions in your webPreferences? Try this:

    webPreferences:{
                
                sandbox: false,
                nodeIntegration:true,
                contextIsolation: false,
                webSecurity: true,
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search