|
| 1 | +# Using custom_main.js |
| 2 | + |
| 3 | +This guide explains how to include and use a `custom_main.js` file in your Electron.NET application for advanced Electron/Node.js customization. |
| 4 | + |
| 5 | +## Why use custom_main.js? |
| 6 | + |
| 7 | +- Register custom protocol handlers (e.g., `myapp://`) — protocols must be registered before the app is fully initialized |
| 8 | +- Integrate Node.js modules (e.g., telemetry, OS APIs) |
| 9 | +- Control startup logic (abort, environment checks) |
| 10 | +- Set up IPC messaging or preload scripts |
| 11 | + |
| 12 | +## Step-by-Step Process |
| 13 | + |
| 14 | +### 1. Create the custom_main.js file |
| 15 | + |
| 16 | +Place your custom logic in `electron/custom_main.js`: |
| 17 | + |
| 18 | +```javascript |
| 19 | +module.exports.onStartup = function(host) { |
| 20 | + // Example: Register a global shortcut for opening dev tools |
| 21 | + const { app, globalShortcut, BrowserWindow } = require('electron'); |
| 22 | + app.on('ready', () => { |
| 23 | + const ret = globalShortcut.register('Control+Shift+I', () => { |
| 24 | + BrowserWindow.getAllWindows().forEach(win => win.webContents.openDevTools()); |
| 25 | + console.log('Ctrl+Shift+I is pressed: DevTools opened!'); |
| 26 | + }); |
| 27 | + }); |
| 28 | + app.on('will-quit', () => { |
| 29 | + globalShortcut.unregisterAll(); |
| 30 | + }); |
| 31 | + return true; |
| 32 | +}; |
| 33 | +``` |
| 34 | + |
| 35 | +### 2. Configure your .csproj to copy custom_main.js to output |
| 36 | + |
| 37 | +Add this to your `.csproj` file: |
| 38 | + |
| 39 | +```xml |
| 40 | +<ItemGroup> |
| 41 | + <None Update="electron\custom_main.js"> |
| 42 | + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> |
| 43 | + <TargetPath>.electron\custom_main.js</TargetPath> |
| 44 | + </None> |
| 45 | +</ItemGroup> |
| 46 | +``` |
| 47 | + |
| 48 | +### 3. Build and run your app |
| 49 | + |
| 50 | +Use the standard build/run commands: |
| 51 | + |
| 52 | +```powershell |
| 53 | +dotnet build |
| 54 | +dotnet run |
| 55 | +``` |
| 56 | + |
| 57 | +Electron.NET will automatically load and execute your `custom_main.js` before initializing the .NET backend. |
| 58 | + |
| 59 | +## Advanced Usage |
| 60 | + |
| 61 | +Use environment variables to control features: |
| 62 | + |
| 63 | + ```javascript |
| 64 | + const env = process.env.ASPNETCORE_ENVIRONMENT || 'Production'; |
| 65 | + if (env === 'Development') { /* enable dev features */ } |
| 66 | + ``` |
| 67 | + |
| 68 | +## Notes |
| 69 | + |
| 70 | +- `custom_main.js` must use CommonJS syntax (`module.exports.onStartup = ...`). |
| 71 | +- Place the file in your source directory and copy it to `.electron` using `.csproj`. |
| 72 | +- Electron.NET will abort startup if `onStartup` returns `false`. |
| 73 | + |
| 74 | +### Complete example is available here [ElectronNetSampleApp](https://github.com/niteshsinghal85/ElectronNetSampleApp) |
0 commit comments