Setting up electron-forge with sveltekit - white screen on package - electron

I am in the process of creating an electron-sveltekit starter. I have the development process working as expected but when I go to package the application it only shows a white screen when it is opened. Does anyone know how to resolve this issue?
Here is a link to my repo - https://github.com/N00nDay/sveltekit-electron-starter
package.json
...
"scripts": {
"start": "cross-env NODE_ENV=dev npm run start:all",
"start:all": "concurrently -n=svelte,electron -c='#ff3e00',blue \"npm run start:svelte\" \"npm run start:electron\"",
"start:svelte": "vite dev",
"start:electron": "electron-forge start",
"package": "cross-env NODE_ENV=production npm run package:svelte && npm run package:electron",
"package:svelte": "vite build",
"package:electron": "electron-forge package",
"make": "electron-forge make",
"build": "vite build",
"preview": "vite preview",
"test": "playwright test",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"test:unit": "vitest",
"lint": "prettier --plugin-search-dir . --check .",
"format": "prettier --plugin-search-dir . --write ."
},
...
forge.config.cjs
module.exports = {
packagerConfig: {
dir: './build'
},
rebuildConfig: {},
makers: [
{
name: '#electron-forge/maker-squirrel',
config: {}
},
{
name: '#electron-forge/maker-zip',
platforms: ['darwin']
},
{
name: '#electron-forge/maker-deb',
config: {}
},
{
name: '#electron-forge/maker-rpm',
config: {}
}
]
};
svelte.config.cjs
import adapter from '#sveltejs/adapter-static';
import { vitePreprocess } from '#sveltejs/kit/vite';
/** #type {import('#sveltejs/kit').Config} */
const config = {
// Consult https://kit.svelte.dev/docs/integrations#preprocessors
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
adapter: adapter({
fallback: '/index.html'
}),
prerender: {
entries: []
}
}
};
export default config;
electron.cjs
const windowStateManager = require('electron-window-state');
const { app, BrowserWindow, ipcMain } = require('electron');
const serve = require('electron-serve');
const path = require('path');
const url = require('url');
const isDev = require('electron-is-dev');
try {
require('electron-reloader')(module);
} catch (e) {
console.error(e);
}
const serveURL = serve({ directory: '.' });
const port = process.env.PORT || 5173;
const dev = !app.isPackaged;
let mainWindow;
function createWindow() {
let windowState = windowStateManager({
defaultWidth: 800,
defaultHeight: 600
});
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
enableRemoteModule: true,
contextIsolation: true,
nodeIntegration: true,
spellcheck: false,
devTools: dev,
preload: path.join(__dirname, 'preload.cjs')
},
x: windowState.x,
y: windowState.y,
width: windowState.width,
height: windowState.height
});
windowState.manage(mainWindow);
mainWindow.once('ready-to-show', () => {
mainWindow.show();
mainWindow.focus();
});
mainWindow.on('close', () => {
windowState.saveState(mainWindow);
});
return mainWindow;
}
function loadVite(port) {
const appURL = app.isPackaged
? url.format({
pathname: path.join(__dirname, '/../build/index.html'),
protocol: 'file:',
slashes: true
})
: `http://localhost:${port}`;
mainWindow.loadURL(appURL);
if (!app.isPackaged) {
mainWindow.webContents.openDevTools();
}
}
function createMainWindow() {
mainWindow = createWindow();
mainWindow.once('close', () => {
mainWindow = null;
});
if (dev) loadVite(port);
else serveURL(mainWindow);
}
app.once('ready', createMainWindow);
app.on('activate', () => {
if (!mainWindow) {
createMainWindow();
}
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
ipcMain.on('to-main', (event, count) => {
return mainWindow.webContents.send('from-main', `next count is ${count + 1}`);
});
preload.cjs
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electron', {
send: (channel, data) => {
ipcRenderer.send(channel, data);
},
sendSync: (channel, data) => {
ipcRenderer.sendSync(channel, data);
},
receive: (channel, func) => {
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
});

Related

How to Auto update using onclick in electronjs

I am developing small application in electronJS and implemented auto update function working fine with log file. but I need with custom window option see attached image could you please update my code and attached my code below. What I am missing refer more references but could not solve this issue.
enter image description here
main.js
`
main.js
// Modules to control application life and create native browser window
const {app, BrowserWindow,ipcMain, dialog } = require('electron')
const path = require('path')
const { autoUpdater }=require('electron-updater')
const log = require('electron-log');
log.transports.file.resolvePath = () => path.join('F:/electronjs/test/electron-quick-start', '/logs/m.log');
log.info("Application version" + app.getVersion())
log.info('Hello, log');
log.warn('loading');
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
// updateInterval = setInterval(() => autoUpdater.checkForUpdates());
autoUpdater.checkForUpdatesAndNotify();
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
autoUpdater.on('update-available',() => {
log.info('update-available')
})
autoUpdater.on('checking-for-update',() => {
log.info('checking-for-update')
})
autoUpdater.on('download-progress',(progressTrack) => {
log.info('download-progress')
log.info(progressTrack)
})
autoUpdater.on('update-downloaded',() => {
log.info('update-downloaded')
})
Package.json
`
{
"name": "electron-quick-start",
"version": "8.0.9",
"description": "A minimal Electron application",
"main": "main.js",
"scripts": {
"start": "electron .",
"pack": "electron-builder",
"package": "electron-builder -p always"
},
"build": {
"publish": [
{
"provider": "github",
"owner": "vansiva",
"repo": "electron"
}
]
},
"keywords": [
"Electron",
"quick",
"start",
"tutorial",
"demo"
],
"author": "GitHub",
"license": "CC0-1.0",
"devDependencies": {
"electron": "^21.2.3",
"electron-builder": "^23.6.0"
},
"dependencies": {
"electron-log": "^4.4.8",
"electron-updater": "^5.3.0"
}
}`
I need auto update with custom popup box

Electron whitescreen without any elements

So I was working on an electron application for quite a while. Then suddenly when typing npm start into the console, it's just a white screen without any elements or scripts.
I think it doesn't load index.html properly, but there aren't any error messages. Before everything worked just fine.
I can't even use the JavaScript Console. When I type anything like
console.log("hello")
It just disappears and returns nothing after pressing Enter.
I don't remember changing anything.
This is my index.js file:
const { app, BrowserWindow, Menu } = require('electron');
const path = require('path');
const remoteMain = require('#electron/remote/main');
const fs = require('fs');
remoteMain.initialize();
if (require('electron-squirrel-startup')) {
app.quit();
}
const createWindow = () => {
const mainWindow = new BrowserWindow({
width: 1600,
height: 1000,
autoHideMenuBar: true,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
devTools: true,
preload: path.join(__dirname, 'preload.js')
},
});
mainWindow.setMenuBarVisibility(false)
mainWindow.setMenu(null)
mainWindow.on('closed', () => {
win = null
})
mainWindow.loadFile(path.join(__dirname, 'index.html'));
remoteMain.enable(mainWindow.webContents)
mainWindow.once('ready-to-show', () => {
mainWindow.show();
})
mainWindow.webContents.openDevTools()
setMainMenu(mainWindow)
};
app.on('ready', createWindow);
function setMainMenu(win) {
const template = [
{
label: 'Filter',
submenu: [
{
label: 'Hello',
accelerator: 'Shift+CmdOrCtrl+H',
click() {
console.log("dont")
}
},
{
label: 'Quit',
accelerator: 'Cmd+Q',
click() {
app.quit()
}
},
{
label: "Reload",
accelerator: "Cmd+R",
click() {
win.reload()
}
},
{
label: "Open dev tools",
accelerator: "f12",
click() {
win.openDevTools()
}
}
]
},
{
label: "Edit",
submenu: [
{ label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" },
{ label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
{ type: "separator" },
{ label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
{ label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" },
{ label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" },
{ label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" }
]}
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});

A JavaScript error occurred in the main process. TypeError: electron.BrowserWindow.addDevToolsExtension is not a function

When I introduced devtron into electron, the program reported an error。
Uncaught Exception:
TypeError: electron.BrowserWindow.addDevToolsExtension is not a function
at Object.exports.install (/electron-quick-start/node_modules/devtron/api.js:13:35)
at App.<anonymous> (/electron-quick-start/main.js:6:24)
at App.emit (node:events:394:28)
I created electron for the first time. I cloned a project from GIT:
git clone https://github.com/electron/electron-quick-start
my code is like this
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path')
app.on("ready", () => {
require('devtron').install();
let mainWindow = new BrowserWindow({
width: 1600,
height: 1200,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('index.html')
mainWindow.webContents.openDevTools(); // 自动打开inspector
ipcMain.on('message',(event,args) => {
console.log(arg)
})
})
my package.json is like this
{
"name": "electron-quick-start",
"version": "1.0.0",
"description": "A minimal Electron application",
"main": "main.js",
"scripts": {
"start": "nodemon --watch main.js --exec \"electron .\""
},
"repository": "https://github.com/electron/electron-quick-start",
"keywords": [
"Electron",
"quick",
"start",
"tutorial",
"demo"
],
"author": "GitHub",
"license": "CC0-1.0",
"devDependencies": {
"electron": "^15.3.1",
"nodemon": "^2.0.15"
}
}
I solved it with this answer,click me see more.
diff --git a/node_modules/devtron/api.js b/node_modules/devtron/api.js
index 3cdabe2..edf8b75 100644
--- a/node_modules/devtron/api.js
+++ b/node_modules/devtron/api.js
## -1,29 +1,27 ##
const electron = require('electron')
+const path = require('path')
-exports.install = () => {
- if (process.type === 'renderer') {
- console.log(`Installing Devtron from ${__dirname}`)
- if (electron.remote.BrowserWindow.getDevToolsExtensions &&
- electron.remote.BrowserWindow.getDevToolsExtensions().devtron) return true
- return electron.remote.BrowserWindow.addDevToolsExtension(__dirname)
- } else if (process.type === 'browser') {
+const resolve = (_dir) => path.resolve(process.cwd(), _dir)
+
+
+exports.install = (session) => {
+ if (process.type === 'renderer' || process.type === 'browser') {
console.log(`Installing Devtron from ${__dirname}`)
- if (electron.BrowserWindow.getDevToolsExtensions &&
- electron.BrowserWindow.getDevToolsExtensions().devtron) return true
- return electron.BrowserWindow.addDevToolsExtension(__dirname)
+ if (session.defaultSession.getAllExtensions &&
+ session.defaultSession.getAllExtensions().devtron) return true
+ return session.defaultSession.loadExtension(resolve(__dirname))
} else {
throw new Error('Devtron can only be installed from an Electron process.')
}
}
-exports.uninstall = () => {
- if (process.type === 'renderer') {
+exports.uninstall = (session) => {
+ if (process.type === 'renderer' || process.type === 'browser') {
console.log(`Uninstalling Devtron from ${__dirname}`)
- return electron.remote.BrowserWindow.removeDevToolsExtension('devtron')
- } else if (process.type === 'browser') {
- console.log(`Uninstalling Devtron from ${__dirname}`)
- return electron.BrowserWindow.removeDevToolsExtension('devtron')
- } else {
+ if (session.defaultSession.getAllExtensions &&
+ !session.defaultSession.getAllExtensions().devtron) return true
+ return session.defaultSession.removeExtension('devtron')
+ }else {
throw new Error('Devtron can only be uninstalled from an Electron process.')
}
}
diff --git a/node_modules/devtron/manifest.json b/node_modules/devtron/manifest.json
index 24613a4..295f752 100644
--- a/node_modules/devtron/manifest.json
+++ b/node_modules/devtron/manifest.json
## -4,8 +4,11 ##
"devtools_page": "static/devtron.html",
"content_scripts": [
{
- "matches": ["*"],
- "js": ["out/browser-globals.js"]
+ "matches": ["http://*/*", "https://*/*"],
+ "js": ["out/browser-globals.js"],
+ "unsafe-inline": true
}
- ]
+ ],
+ "manifest_version": 2,
+ "content_security_policy":"script-src 'self' object-src 'sha256-oUhBdPf7Ru2sGu4k6v1SmxAkpoPTuzvsLrUqElYwDRE='"
}

eletron 'download-progress' does not anything

my build config
"build": {
"mac": {
"target": [
"dmg",
"zip"
],
"publish": {
"provider": "generic",
"url": "http://ip/update/darwin/0.0.1",
"channel": "stable"
}
},
"win": {
"target": [
"squirrel",
"nsis"
]
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": false
}
},
command
"build_mac": "electron-builder --mac"
and main.js
const { app, BrowserWindow, dialog } = require('electron');
const { autoUpdater } = require('electron-updater');
const log = require('electron-log');
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
log.info('App starting...');
app.whenReady().then(function() {
let win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
},
});
win.loadFile('buildprodp/index.html');
win.webContents.openDevTools();
setInterval(() => {
win.webContents.send('submitted-form', `currentVersion - ${app.getVersion()}`);
}, 5000);
init(win);
});
app.on('ready', function() {
setTimeout(() => {
autoUpdater.checkForUpdates();
}, 6000);
});
// autoUpdate codes
const init = win => {
autoUpdater.on('checking-for-update', (ev, err) => {
win.webContents.send('submitted-form', '🔎 Checking for updates');
win.webContents.send('submitted-form', ev);
win.webContents.send('submitted-form', err);
});
autoUpdater.on('update-available', (ev, err) => {
win.webContents.send('submitted-form', '🎉 Update available. Downloading ⌛️');
});
autoUpdater.on('update-not-available', (ev, err) => {
win.webContents.send('submitted-form', '👎 Update not available');
});
autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName) => {
const dialogOpts = {
type: 'info',
buttons: ['Restart', 'Later'],
title: 'Application Update',
message: process.platform === 'win32' ? releaseNotes : releaseName,
detail: 'plz restart',
};
dialog.showMessageBox(dialogOpts).then(returnValue => {
if (returnValue.response === 0) autoUpdater.quitAndInstall();
});
});
autoUpdater.on('error', message => {
win.webContents.send('submitted-form', message);
});
autoUpdater.on('download-progress', progressObj => {
win.webContents.send('submitted-form', 'down start');
});
};
it did work
6s after
autoUpdater.checkForUpdates();
List item
autoUpdater.on('checking-for-update'
autoUpdater.on('update-available',
!!skiping autoUpdater.on('download-progress'!!
autoUpdater.on('update-downloaded'
https://github.com/electron-userland/electron-builder/blob/master/packages/electron-updater/src/AppUpdater.ts#L555
Only 'download-progress' doesn't work
It was a cache problem
Deleting a folder works fine

Using create-react-app with electron-builder

I have create a simple app using create-react-app and made the following changes to package.json
{
"main": "public/electron.js",
"homepage": "./",
"scripts": {
"start": "node scripts/start.js",
"electron-dev": "concurrently \"BROWSER=none yarn start\" \"wait-on http://localhost:3000 && electron .\"",
"preelectron-pack": "yarn build",
"electron-pack": "electron-builder build -m",
"build": "node scripts/build.js",
"prettify": "prettier --write \"src/**/*.js\"",
"precommit": "yarn prettify",
"test": "node scripts/test.js --env=jsdom"
}
}
The electron.js file in the public folder
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const path = require('path')
const url = require('url')
const isDev = require('electron-is-dev')
let mainWindow
function createWindow() {
mainWindow = new BrowserWindow({
width: 1364,
height: 768,
webPreferences: {
webSecurity: false
}
})
mainWindow.setMinimumSize(1364, 768)
mainWindow.loadURL(
isDev
? 'http://localhost:3000'
: url.format({
pathname: path.join(__dirname, '../build/index.html'),
protocol: 'file:',
slashes: true
})
)
mainWindow.webContents.openDevTools()
mainWindow.on('closed', () => (mainWindow = null))
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (mainWindow === null) {
createWindow()
}
})
On running the script electron-pack it gives me this error:
not allowed to load local resource file:///index.html
What could be the possible issue?
react-scripts version: 1.1.5
electron-builder version: 20.28.2
I solved it.
The issue was with BrowserRouter of react-router. I had to change it to HashRouter and now all files and routes load properly.

Resources