I have seen a lot of questions from people trying to console log from the rendering process, this is NOT my problem I have console.log littering my main code and I don't see anything in my console here is my code.
/* eslint-disable no-undef */
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const url = require('url');
/* eslint-enable */
let win;
console.log('console log test');
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 800
});
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
win.on('close', () => {
win = null;
});
console.log('console log test');
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (win == null) {
console.log('console log test');
createWindow();
console.log('console log test');
}
});
I don't see a single log other than the ones produced by electron itself
I've tried throwing errors and those work fine but anything console.* related doesn't work at all, I've tried running it in PowerShell and re-pulling from GitHub, my friend can see the console logs when he pulls the project though so it seems I'm isolated. I've also updated NPM and all modules associated with the project AND I've tried creating a new console and logging to that one but it doesn't seem to show up, am I missing something? I've put hours into this and am ready to give up.
On Windows, if you want to see a console with all your messages from console.log(), you must launch your app with the parameter --enable-logging, for example :
MyApp.exe --enable-logging
I feel your pain. I have this issue on one of my boxes (a Server2012 box). Nothing worked for me until I stumbled across this comment on one of the electron issues threads.
Typically when you install electron you will have a script in your package.json that looks like this.
"scripts": {
"start": "electron .",
}
I changed mine to
"scripts": {
"start": "C:/path/to/project/node_modules/electron-prebuilt/dist/electron.exe .",
}
And I started to get logging from the main electron process in powershell.
Note that if you are using newer versions of electron, you may need to change electron-prebuilt to electron.
How about logging directly into the browser console?
I have found this to be easier for my workflow.
So what I do is to set a listener on the ipcRenderer to the main process and anytime I needed to log a thing from the main, I just emit to the listerner on the renderer.
For instance, in the renderer.js, I set up like so:
pre.ipcRenderer.on("log", (event,log) => {
console.log(log)
});
and in the main, wherever I need to log a piece of code, I just insert this line of code:
window.webContents.send("log", [__dirname]);
My Assumptions with the codes above:
You have set nodeIntegration: false in your webPreference object. This is why codes like __dirname will be unavailable on the renderer process.
As a result of the above, you are using a preloader to load all your required node-specific files.
I defined all of them in my preload.js file and ship them into one giant object which I named window.pre
One of the preloaded modules in the pre object is ipcRenderer. This is why I consumed it as pre.ipcRenderer
All of these is to say that, if you are consuming your nodes directly from the renderer process, you wont need to be bothered by my pre. and if not, now you now why I used it.
Ciao.
Related
I have a Next 10 project where I am trying to use WebWorkers. The worker is being initialized like so:
window.RefreshTokenWorker = new Worker(new URL('../refreshToken.worker.js', import.meta.url))
I also have the Worker defined as
self.addEventListener('message', (e) => {
console.info("ON MESSAGE: ", e)
// some logic with e.data
})
Its also being called like this:
const worker = getWorker() // gets worker that is attached at the window level
worker.postMessage('start')
My next.config.js file is defined as
const nextConfig = {
target: 'serverless',
env: getBuildEnvVariables(),
redirects,
rewrites,
images: {
domains: []
},
future: { webpack5: true },
webpack (config) {
config.resolve.alias['#'] = path.join(__dirname, 'src')
return config
}
}
// more definitions
module.exports = nextConfig
The issue I have is the console.info in the Web Worker definition does not receive the message being sent from postMessage on the build version (yarn build && yarn start) but it does on the dev version (yarn dev). Any ways to fix this?
This is not a solution. But can be a messy way to do the job. This turned out to be a nightmare for me.
I have the same setup as yours. I was initializing web worker as you have shown in your question. I got this idea from the nextjs doc itself: https://nextjs.org/docs/messages/webpack5
const newWebWorker = new Worker(new URL('../worker.js', import.meta.url))
Everything working correctly when I work in dev mode. it is picking up the worker.js file correctly and everything looks alright.
But when I build the nextjs and try it, then web worker won't work. When I dive deeply into the issues, I found out that the worker.js chunk file is created directly under the .next folder. It should come under .next/static/chunk/[hash].worker.js ideally.
I could not resolve this issue in a proper way.
So what i did, i placed my worker.js file directly under public directory. I put my worker.js file transpiled and optimized and put the code in the public/worker.js file.
After this, I modified the worker initialization like this:
const newWebWorker = new Worker('/worker.js', { type: 'module' });
it is working in the production build now. I will report once I get a cleaner solution for this.
i have a problem with electron.
TypeError: Cannot read property 'whenReady' of undefined
i use
node 14.0.1
electron 10.1.2
i run my app
"electron:serve": "vue-cli-service electron:serve",
my background.js
const { app, BrowserWindow } = require('electron')
const { server } = require('feature-server-core')
server.start();
function createWindow () {
// Создаем окно браузера.
const win = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 1280,
minHeight: 800,
closable: true,
center: true,
type: "tool",
titleBarStyle: "hidden",
})
win.menuBarVisible = false;
// и загружаем index.html в приложении.
win.loadURL("google.com")
}
app.whenReady().then(() => {
createWindow()
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()
})
This is the problem related to directly calling the 'index.js' with node like node index.js.
You need to use electron index.js or electron .(if your file is index.js)
electron is building your app.
i solved the same problem just typing in the folder's terminal
npm start
You can use npm start instead of node . to execute your application. If you are using an IDE you have to configure npm with the start option.
I had the same symptom but the underlying problem was completely different from what you find elsewhere on the Internet. Normally, this issue comes from accidentally running main.js with node instead of electron. But in my case the problem was that the NTFS case sensitivity flag was set on the project folder and some subfolders because they were initially created using WSL. This lead to weird things like electron.cmd not being found due to Windows looking for electron.CMD with upper-case extension, etc., and apparently also some similar problem inside Electron itself which made it think we are not inside Electron after all, giving us the non-Electron version of electron which has no app.
The solution was to create a copy of the whole project folder using Windows Explorer, and using that one instead of the original folder. Windows Explorer doesn't preserve the case sensitivity flag, thus creating a copy of the folder clears the flag in all subfolders too. (You can then just delete the old folder.)
More information about case sensitivity in NTFS: https://www.howtogeek.com/354220/how-to-enable-case-sensitive-folders-on-windows-10/
Another cause could be having the environment variable ELECTRON_RUN_AS_NODE=1 set, maybe from some experiment or test a long time ago. Make sure this variable isn't set.
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.
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),
I'm using this boilerplate provided by electron team here. The main process is working but when I use renderer process to create a new window it gives this error
Uncaught TypeError: electron_1.BrowserWindow is not a constructor
at HTMLButtonElement
As I searched it is because of .remote is absent from the compiled typescript to javascript. Code is
main.ts:
import { app, BrowserWindow } from "electron";
import * as path from "path";
let mainWindow: Electron.BrowserWindow;
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
height: 600,
width: 800,
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, "../index.html"));
// Open the DevTools.
// mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.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.
mainWindow = 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 OS X 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 OS X 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 (mainWindow === 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.
renderer.ts:
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
import { BrowserWindow } from "electron";
import * as path from "path";
let childWindow: Electron.BrowserWindow;
const newWindowBtn = document.getElementById('new-window');
newWindowBtn.addEventListener('click', (event) => {
const modalPath = path.join('file://', __dirname, '../modal.html');
childWindow = new BrowserWindow({ width: 400, height: 320 });
childWindow.on('close', () => { childWindow = null; });
childWindow.loadURL(modalPath);
childWindow.show();
});
When I tried to not compile the typescript code to javascript & directly run with .remote it works.
So how to do with typescript code?
I was experiencing this same issue.
When installing the quick start with npm and starting it, a folder called "Dist" was created. There is a renderer.js file in this folder. This is where the typescript renderer file is being compiled into JS.
In my index.html, I changed
<script>
require('./src/renderer.ts')
</script>
To <script>
require('./dist/renderer.js')
</script>
And voila! It worked.
I am not sure why, but none of the Electron Typescript Guides are working because of the renderer.ts not being compiled and required on the fly, and there is an open issue on Github (has been there for months) with no response.
Well, this is my workaround. I am not aware of any negative implications this would cause.