So I've built a trivial application using Electron.
I can start the app using the command 'electron index.html, but not the command 'electron .', even though this is explicitly declared in the package.json
{
"name": "remind-me",
"version": "1.0.0",
"description": "information management tool",
"main": "index.js",
"scripts": {
"start": "electron ."
},
"repository": {
"type": "git",
"url": "tokumk"
},
"dependencies": {
"electron": "^1.6.11"
}
}
a second issue related to window sizing. my BrowserWindow is always the same size regardless of setting it to something else. Here is an example of my index.js. The setting background color is also completely ignored.
index.html
<html>
<head>
</head>
<body>
<div id="container">
<h3>remind me</h3>
<form>
<input type = text action="post"></input>
<input type="submit" value="send" name="submit">
<form>
</div>
</body>
<script>
require('./renderer.js');
</script>
</html>
index.js
const {app, BrowserWindow} = require('electron');
const path = require('path');
const url = ('url');
// window object
let win;
function createWindow(){
// set window size and background color
win = new BrowserWindow({
width: 450,
height: 400,
backgroundColor: '#2e2c29'
});
win.loadURL(url.format({
pathname: path.join(__dir, 'index.html'),
protocol: 'file',
slashes: true
}));
win.webContents.openDevTools();
win.on('closed', ()=> {
win = null;
});
app.on('ready', createWindow);
app.on('window-all-closed', ()=>{
if(process.platform !== 'darwin'){
app.quit();
}
});
}
I think the problem is that you're running the application like electron index.html which just loads index.html in a window and nothing else so if you run electron like: electron index.js I think it would work
Related
I'm starting with electron and for some unknown reason I can't use require() function in renderer process.
Uncaught ReferenceError: require is not defined at index.js:1
package.json
{
"name": "my-electron-app",
"version": "0.1.0",
"author": "your name",
"description": "My Electron app",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [],
"license": "ISC",
"devDependencies": {
"electron": "^12.0.2"
}
}
main.js
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const ipc = ipcMain;
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntergration: true,
contextIsolation: false,
devTools: true,
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('index.html')
win.webContents.openDevTools()
ipc.on("closeApp", ()=>{
console.log("clicked on Close btn")
win.close();
})
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body style="background: white;">
<h1>Hello World!</h1>
<p>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
</p>
<button id="closeBtn">close</button>
<script defer src="index.js"></script>
</body>
</html>
index.js
const { ipcRenderer } = require('electron');
const ipc = ipcRenderer;
var closeBtn = document.getElementById('closeBtn');
closeBtn.addEventListener("click", ()=>{
ipc.send("closeApp");
});
Screenshot of my program
I am doing everything like in the tutorial, I have searched for solution for two days and tried everything, nothing works. I am worried that only I have that problem :v
There's a typo in nodeIntegration (you spelled it nodeIntergration). That's probably the problem
I need help with my simple hello world program based for electron.js.
I was reading the quick guide documentation on the official electronjs.org website.
Esentially I did everything it told me to do on that page including the package.json, package-lock.json, index.html and main.js; and installing electron.js however when I tried to boot up my program in cmd using npm start, I just got 2 messages instead of the program opening.
From there it shows me the cmd command line again waiting for an input which is shown in the picture
I don't know what's wrong and no matter how much I try to edit the package.json and the main.js it still seems to spit out the same error. I was getting so desperate that I just copy and pasted the exact same code in the docs and just edited the author and description as asked in the quick guide.
I am well and truly stuck if anyone has any ideas on how to fix this please let me know, I've also tried some simple troubleshooting, the simple reinstall of the electronjs API, tried administrator cmd, read the forums etc and I can't find anything code will be below..
main.js
const { app, BrowserWindow } = require('electron')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('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()
}
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body style="background: white;">
<h1>Hello World!</h1>
<p>
We are using node <script>document.write(process.versions.node)</script>,
Chrome <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
</p>
</body>
</html>
package.json
{
"name": "my-first-electron",
"version": "1.0.0",
"description": "",
"main": "main.js",
"dependencies": {
"aws-sdk": "^2.814.0",
"electron": "^11.1.0",
"electron.js": "^0.0.1"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "electron ."
},
"keywords": [],
"author": "",
"license": "ISC"
}
i have problem that i dont know what exactly is the cause the problem is, i have simple code in index.js as main and index.html, in main.js the script will send the version of electron to renderer file index.html, when i'm try it before build that script into .exe, the ipcRenderer can get value from sended value, the following image while i run before build into .exe file like this :
image that run before build into .exe
but when i build it into exe file using electron-packager .
it didn't return any value on it after index.js send version in html file, the following image while the following image while i run after build into .exe file like this
image that run after build into .exe
This is my following script and package.json :
index.js
const { app, BrowserWindow,ipcMain } = require('electron')
function createWindow () {
// Create the browser window.
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
enableRemoteModule : false
}
})
const appVersion = process.env.npm_package_version
// and load the index.html of the app.
win.toggleDevTools()
win.loadFile('index.html')
win.webContents.on('dom-ready', () => {
console.log(`Trying to send app version to renderer: ${appVersion}`)
win.send('app-version', appVersion)
console.log(`Current directory: ${process.cwd()}`);
})
}
app.whenReady().then(createWindow)
index.html
<html>
<head>
<title></title>
</head>
<body>
<div id ="appVersion">
</div>
</body>
</html>
<script>
'use strict'
const { ipcRenderer} = require('electron')
ipcRenderer.on('app-version', function (event,store) {
console.log(store);
});
</script>
package.json
{
"name": "test",
"version": "1.0.0",
"description": "test",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "electron ."
},
"author": "",
"license": "ISC",
"dependencies": {
"electron": "^9.2.0",
"electron-packager": "^15.0.0"
}
}
I have just finished working on a test project in electron. The problem is that when I package the app using an electron-packager into an executable, my main.html file does not load up in the window.
However, when I run with npm start it works absolutely fine. I have checked if there is any mistake in the path to my files but that's absolutely fine as well.
Here's my package.json file -
{
"name": "test",
"version": "1.0.0",
"description": "Just a test app",
"main": "src/main.js",
"scripts": {
"start": "electron ."
},
"author": "Ray",
"license": "MIT",
"devDependencies": {
"electron": "^9.0.5"
},
"dependencies": {
"electron-packager": "^15.0.0"
}
}
Here is my main.js
const { app, BrowserWindow } = require('electron')
function createWindow () {
// Create the browser window.
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
// and load the index.html of the app.
win.loadFile('./app/main.html')
}
// 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, 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', () => {
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 (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
Any help will be appreciated. Thanks.
First of all electron-packagershould be part of devDependencies, not dependencies.
Second: How do you pack? If you use an asar File you need to look at the Paths. Those change when packing. So I'd recommend you use something like
win.loadURL(`file://${__dirname}/main.html`)
or
win.loadURL(url.format({
pathname: path.join(__dirname, 'main.html'),
protocol: 'file:',
slashes: true
}));
when loading your html.
UPDATE: index.js file content added.
I have this electron app that is executing some bash scrips(*.sh) files to perform some task.
Everything is working absolutely fine in the development environment but when building the production build for deb installer for Ubuntu platform, everything is working, like opening on the app, other NodeJS stuff, but bash scripts are not executing.
Problem Statement: How to execute shell scripts in the production build of an electron app for Linux(Ubuntu OS). Getting this error
app/terminal_scripts/timer.sh Not Found
Below are the detailed explanation for the app.
**Project Directory Setup**:
ProjectName
|
app > css | images | js | renders
terminal_scripts
node_modules
package.json
package-lock.json
Where inside the app directory, I have all CSS, images, js, HTML, and terminal scripts.
package.json:
{
"name": "timer",
"productName": "Timely",
"version": "1.0.25",
"description": "This desktop app shows you system clock",
"main": "app/js/main/index.js",
"scripts": {
"start": "electron .",
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "nodemon --exec 'electron .'",
"dist": "electron-builder"
},
"homepage": ".",
"keywords": [
"Electron",
"Desktop App"
],
"author": "NotABot Ltd <contact#notabot.com>",
"contributors": [
{
"name": "Not A Bot",
"email": "nab#notabot.com"
}
],
"license": "ISC",
"dependencies": {
"desandro-matches-selector": "^2.0.2",
"electron-context-menu": "^1.0.0",
"electron-is": "^3.0.0",
"fix-path": "^3.0.0",
"isotope-layout": "^3.0.6",
"jquery": "^3.5.0",
"jquery-bridget": "^2.0.1"
},
"build": {
"appId": "com.test.timely",
"productName": "Timely",
"linux": {
"target": "deb",
"category": "System"
}
},
"devDependencies": {
"electron": "^8.1.1",
"electron-builder": "^22.6.0"
}
}
HTML:
<html>
<head>
<title>Timely</title>
</head>
<body>
<button onclick="displayTime()">Display Time</button>
<textarea rows="20" cols="90" id="command-output" disabled="true"></textarea>
<script>
const {app} = require('electron');
function displayTime(){
console.log("button clicked");
let cmd = `bash app/terminal_scripts/timer.sh`;
let completeMessage = 'This is the message';
backgroundProcess(cmd, completeMessage);
}
function getCommandOutput() { return document.getElementById("command-output"); };
function getStatus() { return document.getElementById("status"); };
function appendOutput(msg) { getCommandOutput().value += (msg+'\n'); };
function setStatus(msg) { getStatus().innerHTML = msg; };
function backgroundProcess(cmd, completeMessage){
const process = require('child_process');
var child = process.execFile(cmd, [] , {shell: true} );
appendOutput("Processing......");
child.on('error', function(err) {
appendOutput('stderr: '+err );
});
child.stdout.on('data', function (data) {
appendOutput(data);
});
child.stderr.on('data', function (data) {
appendOutput(data );
});
return new Promise((resolve, reject) => {
child.on('close', function (code) {
console.log(`code is: ${code}`);
if (code == 0){
setStatus(completeMessage);
resolve(1);
}
else{
setStatus('Exited with error code ' + code);
resolve(-1);
}
});
});
}
</script>
</body>
</html>
Bash Script:
#!/bin/bash
timer="$(date)"
echo "$timer"
Permission is set 777 for this shell file
Platform Information:
OS: Ubuntu 18.04.4 LTS
NodeJS: 13.6.0
NPM: 6.14.5
Electron: 8.1.1
Electron Builder: 22.6.0
index.js
const {app, BrowserWindow, Menu, Tray, ipcMain, MenuItem} = require('electron');
const path = require('path');
const contextMenu = require('electron-context-menu');
let splashWindow;
function createMainWindow(){
mainWindow = new BrowserWindow({
minHeight: 700,
minWidth: 800,
webPreferences: {
nodeIntegration: true,
webviewTag: true
},
show: false
});
//For dev only
// mainWindow.webContents.openDevTools();
mainWindow.loadFile('app/renderer/index.html');
mainWindow.maximize();
}
app.on('ready', () =>{
createMainWindow();
});
Another way is to move flies to a new directory outside app directory and call it as extraResources.
Inside that directory you can add all your bash files and for production you can use below method.
let urlPath = path.join(process.resourcesPath, '/extraResources/')
and then use let cmd = `${urlPath}timer.sh`;
I have created a new directory alongside the app directory called the termainal_scripts.
Inside this, I have my bash file timer.sh.
I figured out how to execute shell scripts, in production by using process.resourcesPath inside path.join().
So, let the fixed path be as:
let fixedURL = path.join(process.resourcesPath, '/terminal_scripts/');
Then the command to execute will be:
let cmd = `${fixedURL}timer.sh`