title: Electron | onbeforeunload prevents reloading
body: <p>I'm trying to develop an app with a separate settings window (in electron). When the settings window is open and the main window is closed, I want to prevent the closing of the main window and focus the settings window.</p>
  
  <p>Right now I do this as following:</p>
  
  <pre><code>window.onbeforeunload = e =&gt; {
      console.log(e);
      if(settingsWindow) {
          settingsWindow.focus();
          e.returnValue = false;
      }
      else e.returnValue = true;
  };
  </code></pre>
  
  <p>This although prevents reloading the window, which I don't want.
  So I'm asking for a different preventing method or a way to detect if it is a reload or a close.</p>
  
  <p>Greeting Elias =)</p>
  
  <p><strong>EDIT/Solution:</strong>
  utilize <code>ipcMain</code> and <code>ipcRenderer</code> to handle everything with creating windows in the main process. There you can catch and prevent the <code>close</code> event.</p>
  
  <p><strong>MAIN.JS</strong></p>
  
  <pre><code>const {ipcMain} = require("electron");
  ...
  ipcMain.addListener("ASYNC_MSG", (event, arg) =&gt; {
      switch(arg) {
          case "OPEN_SETTINGS": createSettingsWindow(); break;
      }
  });
  
  ...
  
  mainWindow.addListener("close", e =&gt; {
      if(settingsWindow) {
          e.preventDefault();
          e.returnValue = false;
          settingsWindow.focus();
      }
      else e.returnValue = true;
  
  });
  </code></pre>
  
  <p><strong>RENDERER.JS</strong></p>
  
  <pre><code>const {ipcRenderer} = require("electron");
  ...
  ipcRenderer.send("ASYNC_MSG", "OPEN_SETTINGS");
  </code></pre>