package.json:
{
"name": "electronapp",
"version": "1.0.0",
"description": "electron auto-launch",
"main": "index.js",
"scripts": {
"start": "electron .",
"build": "electron-packager . --all"
},
"author": "ivie",
"license": "ISC",
"devDependencies": {
"Q": "^1.0.0",
"asar": "^0.13.0",
"electron": "^1.7.6",
"electron-packager": "^9.1.0",
"electron-prebuilt": "^1.4.13",
"fs-jetpack": "^1.2.0",
"grunt-electron-installer": "^2.1.0",
"rcedit": "^0.9.0"
},
"dependencies": {
"auto-launch": "^5.0.1"
}
}
index.js:
var electron = require('electron');
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var path = require('path');
app.on('ready', ()=>{
var mainwindow = new BrowserWindow({
width: 1200,
height: 800,
icon: "favicon.ico",
frame:true,
title:'Menuboard',
fullscreen: false,
autoHideMenuBar: false
})
mainwindow.openDevTools();
mainwindow.loadURL('https://www.google.com');
mainwindow.on('closed', function() {
mainwindow = null;
});
});
app.on('window-all-closed', function() {
if(process.platform != 'darwin')
app.quit();
})
I have generated an electron .exe using this code. It's getting executed when I'm double clicking on it. But, I want to run it on windows startup. I got to know about auto-launch. But, I'm not sure how to use it in my application? Any help would be appreciated.
Load auto-launch module:
const AutoLaunch = require('auto-launch');
Then add this after app.on('ready', ()=>{:
let autoLaunch = new AutoLaunch({
name: 'Your app name goes here',
path: app.getPath('exe'),
});
autoLaunch.isEnabled().then((isEnabled) => {
if (!isEnabled) autoLaunch.enable();
});
FYI this is now provided by Electron out of the box:
https://electronjs.org/docs/api/app#appsetloginitemsettingssettings-macos-windows
Example:
const electron = require("electron")
electron.app.setLoginItemSettings({
openAtLogin: arg.settings.startOnStartup,
path: electron.app.getPath("exe")
});
EDIT
Based on new comments, this may be out of date. Consider trying Timur Nugmanov's answer first.
At current electron release(19.0.0), the code below works fine:
app.setLoginItemSettings({
openAtLogin: true
})
Related
I am geeting the follwoing error when I try to run the application in production mode.
Running in development is working fine.Whe I try to run the app on production mode it is showing error.Error is file not found but file is already in the particular location.
at rejectAndCleanup (electron/js2c/browser_init.js:217:1457)
at Object.failListener (electron/js2c/browser_init.js:217:1670)
at Object.emit (events.js:315:20) {
errno: -6,
code: 'ERR_FILE_NOT_FOUND',
My package.json file
{
"name": "electron-react-webpack-boilerplate",
"version": "1.15.0",
"description": "Minimal Electron, React, PostCSS and Webpack boilerplate to help you get started with building your next app.",
"license": "MIT",
"private": false,
"repository": {
"type": "git",
"url": "https://github.com/alexdevero/electron-react-webpack-boilerplate.git"
},
"homepage": "",
"bugs": {
"url": "https://github.com/alexdevero/electron-react-webpack-boilerplate/issues"
},
"author": {
"name": "Alex Devero",
"email": "deveroalex#gmail.com",
"url": "https://github.com/alexdevero"
},
"keywords": [
"app",
"boilerplate",
"electron",
"open",
"open-source",
"postcss",
"react",
"reactjs",
"source",
"webpack"
],
"engines": {
"node": ">=9.0.0",
"npm": ">=5.0.0",
"yarn": ">=1.0.0"
},
"browserslist": [
"last 4 versions"
],
"main": "index.js",
"scripts": {
"prod": "cross-env NODE_ENV=production webpack --mode production --config webpack.build.config.js && electron --noDevServer .",
"start": "cross-env NODE_ENV=development webpack serve --hot --host 0.0.0.0 --config=./webpack.dev.config.js --mode development",
"build": "cross-env NODE_ENV=production webpack --config webpack.build.config.js --mode production",
"package": "npm run build",
"postpackage-windows": "electron-packager ./dist --out=./builds --platform=win32",
"postpackage": "electron-packager ./ --out=./builds"
},
"dependencies": {
"#material-ui/core": "^4.11.3",
"#material-ui/icons": "^4.11.2",
"#material-ui/lab": "^4.0.0-alpha.57",
"ffmpeg-static": "^4.2.8",
"fluent-ffmpeg": "^2.1.2",
"material-ui-dropzone": "^3.5.0",
"material-ui-image": "^3.3.1",
"postcss": "^8.2.8",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-player": "^2.9.0",
"react-router-dom": "^5.2.0",
"react-window": "^1.8.6",
"validator": "^13.5.2"
},
"devDependencies": {
"#babel/core": "^7.13.10",
"#babel/preset-env": "^7.13.10",
"#babel/preset-react": "^7.12.13",
"babel-loader": "^8.2.2",
"cross-env": "^7.0.3",
"css-loader": "^5.1.1",
"electron": "^12.0.0",
"electron-devtools-installer": "^3.1.1",
"electron-packager": "^15.2.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.1",
"mini-css-extract-plugin": "^1.3.9",
"notistack": "^1.0.5",
"postcss-import": "^14.0.0",
"postcss-loader": "^5.1.0",
"postcss-nested": "^5.0.5",
"postcss-preset-env": "^6.7.0",
"postcss-pxtorem": "^5.1.1",
"style-loader": "^2.0.0",
"webpack": "^5.24.4",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
}
}
and electron main file
'use strict'
// Import parts of electron to use
const { app, BrowserWindow,protocol } = require('electron')
const path = require('path')
const url = require('url')
// 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 mainWindow
// Keep a reference for dev mode
let dev = false
// Broken:
// if (process.defaultApp || /[\\/]electron-prebuilt[\\/]/.test(process.execPath) || /[\\/]electron[\\/]/.test(process.execPath)) {
// dev = true
// }
if (process.env.NODE_ENV !== undefined && process.env.NODE_ENV === 'development') {
dev = true
}
// Temporary fix broken high-dpi scale factor on Windows (125% scaling)
// info: https://github.com/electron/electron/issues/9691
if (process.platform === 'win32') {
app.commandLine.appendSwitch('high-dpi-support', 'true')
app.commandLine.appendSwitch('force-device-scale-factor', '1')
}
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1024,
height: 768,
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule:true,
webSecurity:false
}
})
// and load the index.html of the app.
let indexPath
if (dev && process.argv.indexOf('--noDevServer') === -1) {
indexPath = url.format({
protocol: 'http:',
host: 'localhost:8080',
pathname: 'index.html',
slashes: true
})
}
else {
indexPath = url.format({
protocol: 'file:',
pathname: path.join(__dirname, 'dist', 'index.html'),
slashes: true
})
console.log('prod')
}
mainWindow.loadURL(indexPath).catch(err=>{
console.log(err)
})
// Don't show until we are ready and loaded
mainWindow.once('ready-to-show', () => {
mainWindow.show()
// Open the DevTools automatically if developing
if (dev) {
const { default: installExtension, REACT_DEVELOPER_TOOLS } = require('electron-devtools-installer')
installExtension(REACT_DEVELOPER_TOOLS)
.catch(err => console.log('Error loading React DevTools: ', err))
// mainWindow.webContents.openDevTools()
}
})
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// 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
})
protocol.interceptFileProtocol('file', (request, callback) => {
const url = request.url.substr(7) /* all urls start with 'file://' */
callback({ path: path.normalize(`${__dirname}/${url}`)})
}, (err) => {
if (err) console.error('Failed to register protocol')
})
}
// 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 (mainWindow === null) {
createWindow()
}
})
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`
I am trying to locate the element using Javascript, appium, WebdriverIo and Mocha. The app is getting launch on emulator but getting error while locating element.Any other approach that can be used?
The testclass.js file code is given below:
const wdio = require("webdriverio");
//example capabilities
const opts = {
port: 4723,
capabilities: {
platformName: "Android",
deviceName: "emulator-5554",
app: "D:demo.apk",
appPackage: "com.somepackage",
appActivity: "com.somepackage.acivity",
newCommandTimeout: 500,
noReset: "true",
automationName: "UiAutomator2"
}
};
var client = wdio.remote(opts);
describe('Test App launch', function () {
this.timeout(15000);
it('register', async function(){
// This is the error line below
**const elm = await client.findElement("resource-id","goRegistrationButton")**
elm.click();
});
});
package.json file:
{
"name": "testclass",
"version": "1.0.0",
"description": "Automating app",
"main": "testclass.js",
"scripts": {
"test": "testclass.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"mocha": "^6.0.2",
"typescript": "^3.3.4000",
"webdriverio": "^5.7.6"
},
"devDependencies": {
"ts-node": "^8.0.3"
}
}
I am expecting to click the element for the native android app using javascript and webdriverIO
I'm building an app and all works fine while I'm in developer mode. Everythink works as it should. But when I package my app with electron-builder, app opens but it doesnt start express server and app doesnt work properly.
Here is my package.json code
{
"name": "artros",
"version": "1.0.0",
"description": "Artros",
"author": "MC3",
"license": "ISC",
"main": "start.js",
"scripts": {
"pack": "build --dir",
"dist": "build"
},
"build": {
"appId": "com.artros.app",
"productName": "Artros",
"win": {
"target": "portable",
"icon": "build/icon.ico"
},
"mac": {
"target": "dmg"
}
},
"dependencies": {
"body-parser": "^1.18.3",
"ejs": "^2.5.7",
"electron-pdf-window": "^1.0.12",
"express": "^4.16.2",
"multer": "^1.3.0",
"nodemailer": "^4.6.4",
"path": "^0.12.7"
},
"devDependencies": {
"electron": "^1.8.2"
}
}
and here is my start.js code
const cluster = require('cluster');
if (cluster.isMaster) {
require('./main.js'); // your electron main file
cluster.fork();
} else {
require('./app.js'); // your server code
}
and my main.js code
var electron = require('electron');
var browserWindow = electron.BrowserWindow;
var app = electron.app;
app.on('ready', function(){
var appWindow;
//appWindow
appWindow = new browserWindow({
width:1120,
height:620,
webPreferences: {
plugins: true
},
icon: __dirname + '/public/icon/icon.png'
});
appWindow.loadURL('file://' +__dirname + '/public/prva.html');
//appWindow.webContents.openDevTools();
});
// close app after all windows are closed
app.on('window-all-closed', () => {
app.quit()
})
If anybody has any idea what is the problem, please post it. Thanks
I had something similar happen to me. The challenge was that if you use fork() the application path changes. So I would recommend that you check __dirname in all of your files especially the ones in your forked process (e. g. app.js). I wouldn't be surprised if some of them don't make sense anymore.
I found the solution. The problem really was in my app.js code. At one detination I needed to add (path.join(__dirname, './path/to/file')). Guys thanks for your help.
I'm having some issues while trying to glue together this two things.
Let me give you some context: I'm trying to build a desktop application based on a web application that I've developed in react and it's fully operative and the build process of react is done without any errors nor issues. The problem comes when I try to glue Electron + a React Built Project.
I'm having the following structure:
/ dist
/ node_modules
/ react-mobx-router
/ build
/ static
/ js
main.05ef4655.js
/ css
main.9d8efafe.css
index.html
index.js
At the index.js i have the following code that's basically the sample boilerplate code from electron demo app:
'use strict';
const electron = require('electron');
const app = electron.app;
// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();
// prevent window being garbage collected
let mainWindow;
function onClosed() {
// dereference the window
// for multiple windows store them in an array
mainWindow = null;
}
function createMainWindow() {
const win = new electron.BrowserWindow({
width: 1280,
height: 720,
minWidth: 1280,
minHeight: 720
});
win.loadURL(`file://${__dirname}/react-mobx-router/build/index.html`);
//win.loadURL(`http://localhost:3000`);
win.on('closed', onClosed);
return win;
}
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (!mainWindow) {
mainWindow = createMainWindow();
}
});
app.on('ready', () => {
mainWindow = createMainWindow();
});
I also have to manually change some paths at the react built index.html so it will look like:
<link href="./static/css/main.9d8efafe.css" rel="stylesheet">
instead of:
<link href="/static/css/main.9d8efafe.css" rel="stylesheet">
The second one get's the following errors:
file:///D:/static/css/main.9d8efafe.css Failed to load resource: net::ERR_FILE_NOT_FOUND
main.05ef4655.js Failed to load resource: net::ERR_FILE_NOT_FOUND
The point is that, when I launch the Electron app with yarn start (changing the paths I've told you previously) it launches without any error nor issue but only a blank screen, if I go to the files and look for them, they are correct and the code is inside, bundled and all that react-create-app stuff does.
This is the default configuration of the package.json that comes with Electron and I haven't modified:
{
"name": "app",
"productName": "App",
"version": "0.0.0",
"description": "",
"license": "MIT",
"repository": "user/repo",
"author": {
"name": "",
"email": "",
"url": ""
},
"scripts": {
"test": "xo",
"start": "electron .",
"build": "electron-packager . --out=dist --asar --overwrite --all"
},
"files": [
"index.js",
"index.html",
"index.css"
],
"keywords": [
"electron-app",
"electron"
],
"dependencies": {
"electron-debug": "^1.0.0"
},
"devDependencies": {
"devtron": "^1.1.0",
"electron-packager": "^8.0.0",
"electron": "^1.0.1",
"xo": "^0.16.0"
},
"xo": {
"esnext": true,
"envs": [
"node",
"browser"
]
}
}
Also this is the package.json of my React Project:
{
"name": "react-mobx",
"version": "0.1.0",
"private": true,
"devDependencies": {
"custom-react-scripts": "0.0.23",
"mobx-react-devtools": "^4.2.11"
},
"dependencies": {
"mobx": "^3.1.4",
"mobx-react": "^4.1.2",
"mobx-react-router": "latest",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-router": "latest"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
Note that the React App is fully functional if I don't make use of Electron.
That's why I ask for your wisdom, mates. I need some light here so I can keep moving on with this project. Hope you can help me with this issue and I've provided you with enough information. If you need more info, just let me know.
Warm regards,
Alex.
I'm no React hero (by a long chalk) but I am able to run, hot reload and release build using the schema set out by this boilerplate: electron-es6-react. I added some conditional code to main.js (below) for builds. There are no doubt much better solutions.
You definitely need to merge your React package.json with Electron's.
var isDev = process.env.APP_DEV ? (process.env.APP_DEV.trim() == "true") : false;
if (isDev) {
// only add this during development
require('electron-reload')(__dirname, {
electron: path.join(__dirname, 'node_modules', '.bin', 'electron')
});
}
package.json
{
"name": "electron-es6-react",
"version": "0.1.0",
"description": "template",
"license": "MIT",
"production": false,
"version-string": {
"CompanyName": "Cool Co.",
"FileDescription": "template",
"OriginalFilename": "template",
"ProductName": "template",
"InternalName": "template"
},
"main": "main.js",
"scripts": {
"start": "APP_DEV=true electron -r babel-register .",
"package-mac": "electron-packager . --overwrite --tmpdir=false --platform=darwin --arch=x64 --prune=true --out=release-builds",
"package-win": "electron-packager . --overwrite --tmpdir=false --asar=true --platform=win32 --arch=ia32 --prune=true --out=release-builds"
},
"dependencies": {
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-register": "^6.3.13",
"fs-jetpack": "^0.12.0",
"react": "^15.3.2",
"react-dom": "^15.3.2",
"react-images": "^0.5.2"
},
"devDependencies": {
"electron": "^1.4.3",
"electron-packager": "^8.5.2",
"electron-reload": "^1.1.0"
}
}