Electron window shows a screenshot of the screen - javascript

So I have an electron app named main.js which I start with npm start. I've set the start script in package.json to electron main.js and have also tried electron .. When running npm start, everything starts without any errors but the electron window only shows a snapshot of what was on the screen when I started it. I've tried refreshing it but nothing seems to work. Here is how it looks:
Image
It should view localhost:3001 but it doesn't. I've also tried to run electron . directly in the terminal but that gives me electron: command not found. When running ./node_modules/electron/dist/electron . it starts as it should but the same problem occurs. Here is main.js:
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const core = require('./app');
let mainWindow
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: { webSecurity: false },
nodeIntegration: false,
})
mainWindow.loadURL('http://localhost:3001');
// mainWindow.setFullScreen(true)
// mainWindow.setMenu(null);
mainWindow.webContents.openDevTools()
mainWindow.on('closed', function () {
mainWindow = null
})
console.log('Electron window ready')
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
app.quit()
})
core.start()

It seems you didn't install Electron globally, for that you need to run npm install -g Electron
Replace mainWindow.loadURL('http://localhost:3001'); With:
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, "index.html"),
protocol: "file:",
slashes: true
})
);

You have not shared your package.json file, but I will guess you did not run npm install --save electron in your terminal.
Also, instead of:
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
you want to write it like so:
const electron = require('electron');
const { app, BrowserWindow } = electron;
I would review ES6 destructuring and unless you did not share the code with us, you should start your electron project by assuring that the app object is ready and loading your file like so:
let mainWindow;
app.on('ready', () => {
mainWindow = new BrowserWindow({});
mainWindow.loadURL(`file://${__dirname}/main.html`);
});
You will notice I declared an empty mainWindow variable to take care of any scoping issues you may have as you may have to use mainWindow in other functions as well.

Related

ES6 import of electron modules with Vite/Vue fails

I am trying to use electron with latest Vite 2/Vue 3. I have setup two versions of electron's main file so I can test and work with both dev server and the build:
dev version loading the localhost:3000 (from npm run dev) with loadURL
another version loading the built version (from npm run build)from the dist folder with loadFile
I have set in the new BrowserWindow options:
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
preload: path.join(app.getAppPath(), 'electron.preload.js')
}
The app starts just fine in Electron in both dev and build version, loads all assets and without any security errors. However, when I try to import any module from 'electron' in my project, in example:
import electron from 'electron';
I get the error:
Uncaught TypeError: path.join is not a function
at node_modules/electron/index.js (index.js:4)
I tried to check path and __dirname, to see if they work in my project:
import * as path from 'path';
console.log(path);
console.log(path.join);
console.log(__dirname);
And these do trace out the following in Electron dev panel:
If I try to import path differntly:
import path from 'path'
console.log(path);
console.log(path.join);
I get the following result:
In any case, path.join is undefined. And now I am pretty much stuck on how to go on.
I can also add that I want to use fs-extra, but this also fails:
import fs from 'fs-extra';
[Edit: added the preload in webPreferences]
I believe Vite transforms things a lot behind the scenes. Thankfully #electron/remote provides an alternate way to fetch things:
electron.js:
const { app, BrowserWindow } = require("electron");
const Remote = require("#electron/remote/main");
Remote.initialize();
// ...
app.on("ready", () => {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
});
Remote.enable(mainWindow.webContents);
mainWindow.loadFile(path.resolve("./dist", "index.html"));
});
// ...
Component.tsx:
import type { BrowserWindow } from "electron";
const Component: React.FC = () => {
const app = window.require("#electron/remote");
const win: BrowserWindow = app.getCurrentWindow();
// ...
}
Not sure if this is the best solution, but it works for me with Vite + Electron + React.

How to create an executable file from React-Electron project

I have a web app created with React. I want to create the desktop version of that app. To do that, i added electron.js file in the public folder. Inside the electron.js file is the basic electron code that take index.html and turn it to a desktop app that looked like this:
const { app, BrowserWindow } = require('electron')
const path = require("path");
const isDev = require("electron-is-dev");
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadURL(isDev ? "http://localhost:3000" : `file://${path.join(__dirname, "../build/index.html")}`);
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
The app is works and I don't add any electron code to the src folder. How can i get the executable for Windows, Mac, and Linux in my React-Electron code? My machine run on linux
You could use a library called electron-builder.
Install the library with npm install or yarn add then add a new task to package.json to run electron-builder for example to build an app to windows, linux and mac you can run, these can be put in package.json as well so you don't need to type it everytime you want to build. It's also possible to build an app using a programmatic API. You'll find more details in the docs, there are also tutorials and guides.
electron-builder -mwl

electron-builder shows white page after compile

I trying to build an Electron app. For that I'm using the following respos:
https://github.com/electron/electron-quick-start
https://github.com/electron-userland/electron-builder
In devoplement mode (electron .) everything works fine. But when I build the app and starting it, it just shows me a blank page without any errors in the dev console or build log.
Why doesn't it work in production? All my files are in one direction:
index.html
main.js
renderer.js
package.json
I didn't changed much in the base main.js file:
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
frame: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
webSecurity: false
}
})
// and load the index.html of the app.
//mainWindow.loadFile('index.html')
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
// 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)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') app.quit()
})
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()
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
That's because your output html in production should be located elsewhere, btw I'm using angular with electron and the output is in the dist folder, but I don't use url.format: try with mainWindow.loadURL(`file://$_dirname/index.html`)
or if you have a dist folder mainWindow.loadURL(`file://$_dirname/dist/index.html')
Try changing also
app.whenReady() by app.on("ready",createWindow)
Hope it works afterwards

My electron app is not starting without any logging

So I am trying to make an electron app with angular(Typescript version) and it will not start at all, I have integrated Electron-log which does not do anything (that is the reason i think it does not start at all).
const path = require('path');
const url = require('url');
const log = require('electron-log');
log.transports.file.level = 'debug';
log.transports.file.format = '{h}:{i}:{s}:{ms} {text}';
log.transports.file.file = __dirname + './log.txt';
log.transports.file.streamConfig = { flags: 'w'};
log.info('message');
// Keep a global reference of the window object, if we don't the window will be closed
// automagically when the JS object is Garbage Collected. (GC from here on out)
let win;
try {
const createWindow = () => {
// set timeout to render the window not until the Angular compiler is ready to show the project
//create the browser window
win = new BrowserWindow({
width: 800,
height: 600,
icon: path.join(__dirname, 'favicon.ico'),
});
//and load the app
win.loadURL(url.format({
pathname: path.join(__dirname, 'resources/app/angular-flask/index.html'),
protocol: 'file:',
slashes: true
}));
// Emitted when the window is closed
win.on('closed', () => {
// Dereference the window object
win = null;
});
};
// This method will be called when Electron has finished initialization and is ready to
// create browser windows . Some API's can only be used after this event happens.
app.on('ready', createWindow);
// Quit when all windows are closed
app.on('windows-all-closed', () => {
// On macOS applications might stay active untill user quits with cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
// On macOS sometimes a window is recreated when the dock icon is clicked and there are no other
// windows open
if (win === null) {
createWindow();
}
});
} catch(e) {
log.error(e)
}
Above is my Electron Production code, also available on pastebin Can anyone explain why this might be happening and offer a solution?
EDIT: It did not work before I integrated electron-log. Also the angular front-end works when i start that through npx lite-server.
EDIT2: Here is my Package.json and my updated main.js code electron.prod.js Also I am using electron packager.
It looks like app is not defined.
Can you please try adding the following lines at the beginning of your file.
const electron = require('electron');
const app = electron.app;
So to fix my issue I went back to the tutorial I followed and checked the package.json that was used there and slowly added and updated everything I had into that package.json.
When it was still working I ported it to my own package.json and with that it worked.

Electron index.html not loading after building the app

I have an electron app that works perfectly fine before bundling it with electron-builder. After bundling it and opening the app, I get the following error :
Not allowed to load local resource: file:///tmp/.mount_displa4VwuQh/resources/app.asar/file:/tmp/.mount_displa4VwuQh/resources/app.asar/build/index.html
In the build folder I have the electron.js file and index.html and since the app is starting electron.js and thus index.html got bundled correctly.
Here is my electron.js app entry point(basically boilerplate):
const { app, BrowserWindow } = require('electron')
const url = require('url')
const path = require('path')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, './index.html'),
protocol: 'file:',
slashes: true
}));
// Emitted when the window is closed.
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
})
}
// 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.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// 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 (win === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
When trying with loadFile() instead of loadUrl() I get the same error, but with this path instead : file:///tmp/.mount_displa4VwuQh/resources/app.asar/index.html
Any idea what is wrong? Thanks in advance!
So it looks like my problem was caused from improper packaging after all. Adding this in package.json "build" configuration fixed it:
"directories": {
"buildResources": "build",
"app": "build"
}
check once your directory path for index.html
I think you follow any tutorial and do not verify your path just once check I hope this will resolve your issue.
pathname: path.join(__dirname, ./src/index.html),

Categories