How to disable 'devTools' in Capacitor + Electron app - electron

To disable devTools we need to access webPreferences through BrowserWindow, However BrowserWindow is not available directly from the Electron app. So how do we access webPreferences to diable the devTools?
Without Capcitor Below code snippet works perfectly fine
const browserWindow = new BrowserWindow({
.....
webPreferences: { devTools: false}
})

let config: CapacitorElectronConfig = {
mainWindow: {
windowOptions: {
webPreferences: {
devTools: false
}
}
}
}
While creating Capacitor Electron app, we just need to pass on the configuration.
const myCapacitorApp = createCapacitorElectronApp(config);

Related

electron app update now crashing on http require statement

I made a electron app a couple years ago. now like to update for a little bit diiferint usage.
When I try to run this after updating electron and libraries and import it is failing on the http requirement.
The long ago compiled app still works, but even the code for that if i copy it to new project also failed on this require line.
Error in the console
ReferenceError: Can't find variable: require
renderer.js:62
And below are the codes
browser setup in index.js
const path = require('path');
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
app.quit();
}
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 200,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
}
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Open the DevTools.
//mainWindow.webContents.openDevTools();
};
failing request in renderer.js
/* placeCall
* Grab the SIP uri from the input box and send it to the codec.
* Requires an account on the codec that can make calls.
* Send the authorization in the http header.
*/
function placeCall(){
var uri = document.getElementById("sipuri").value;
var xmldoc = '<Command><Dial command="true"><Number>' + uri + '</Number></Dial></Command>';
var xmlLength = xmldoc.length;
var sysIp = document.getElementById("sysip").value;
// console.log("XMLDOC: " + xmldoc);
var http = require("https"); <- CRASHES HERE ON LINE 62!
var options = {
"method": "POST",
"hostname": sysIp,
"port": null,
"path": "/putxml",
"rejectUnauthorized": false,
"headers": {
"content-type": "text/xml",
"content-length": xmlLength,
"authorization": "Basic dkeicjsmcielwoslkdddddd"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(xmldoc);
req.end();
}
the error is in the browser. seems like it has to run as electron app.
That must be that require is really a node.js operation.
Maybe this question is repeated elsewhere and this one can be deleted.

Electron Deeplink is not working, it does not respond at all with "gotTheLock", unless I run it directly via CMD line calling electron.exe

I've been trying to get deeplinks to work to do oauth for like 4 weeks:
on different boilerplates
on raw quick start of electron
on electron-forge with webpack.
None of them work while in dev mode, and only does while packaged.
I do not understand why it only works if I target command line the electron.exe and pass my app. OR when the app is packaged. If it's in development mode, it simply does not work.
I think? that the gotTheLock runs app.quit(), because in instances where I put the createWindow() outside of the lock if/else function, a window briefly opens and then closes immediately. For some reason it's opening a new instance completely? When createWindow() is inside, I basically see nothing happen.
I'm on Windows, I see nothing about forge that would cause issues or need extra setup in the forge config/package.json since I am on Windows
There's something fundamental flying over my head. Currently, my latest attempt is with the new 6.0 electron-forge from here with the following npm command to generate:
npm init electron-app#latest my-app --template=webpack cd my-app npm start
Here is my "main" which is called index.js here.
index.js
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
app.quit();
}
let mainWindow;
if (process.defaultApp) {
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient('electron-fiddle', process.execPath, [path.resolve(process.argv[1])])
}
} else {
app.setAsDefaultProtocolClient('electron-fiddle')
}
const createWindow = () => {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Open the DevTools.
mainWindow.webContents.openDevTools();
};
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
app.quit()
} else {
app.on('second-instance', (event, commandLine, workingDirectory) => {
// Someone tried to run a second instance, we should focus our window.
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore()
mainWindow.focus()
}
})
app.on('ready', createWindow);
}
// 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.
// 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 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 (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 import them here.
ipcMain.on('shell:open', () => {
const pageDirectory = __dirname.replace('app.asar', 'app.asar.unpacked')
const pagePath = path.join('file://', pageDirectory, 'index.html')
shell.openExternal(pagePath)
})
I've tried so many iterations i'm honestly just lost. What's wrong with this that the electron-forge dev mode doesn't like?
As far as any other code is concerned, it's "as-is" from that npm command with the latest 6.0 electron-forge with webpack template. Only the index.js was modified

launching Theia based electron app (artifact/package) isn't working

Almost new in using playwright. Exploring the things and checking what we can do with this tool.
I am trying to launch our Theia based electon app in Ubuntu 18.04 with below source.
const { _electron: electron } = require('playwright');
//const { _electron } = require('playwright');
//import { test, expect, Page } from '#playwright/test';
(async () => {
// Launch Electron app.
const electronApp = await electron.launch('./my_executable_file_path');
//this executable is an artifact/packgae
})();
test.describe('New Todo', () => {
test('should allow me to add todo items', async ({ page }) => {
//let's not do anything before the app launch.
});
});
In my package.json file, i have this already
"devDependencies": {
"#playwright/test": "^1.20.2",
I can successfully run test cases based on the browser but not able to launch the electron app.
electron.launch: Cannot find module 'electron/index.js'
We don't have this index.js in our jenkins generated artifact.
This is how I launched electron successfully
const electronApp = await _electron.launch({
args: ['theia-electron-main.js'],
cwd: 'cube-electron/apps/studio/electron/scripts'
});

Can't open Electron webview links with target = blank

I'm using Electron I have a webview which display an external website but I can't succeed to show the additional window normally opened by links on this site and which have target = _blank.
Mentions légales
I tried with
webpreferences="nativeWindowOpen=yes" allowpopups
But it didn't change.
With a webview, you can actually handle these on the main process quite easily.
Which also allows you to disable nodeIntegration should that be a requirement.
// Listen for web contents being created
app.on('web-contents-created', (e, contents) => {
// Check for a webview
if (contents.getType() == 'webview') {
// Listen for any new window events
contents.on('new-window', (e, url) => {
e.preventDefault()
shell.openExternal(url)
})
}
})
After digging into the documentation I wrote this code (code located in the renderer):
const {BrowserWindow} = require('electron').remote
..........
webview1.addEventListener('new-window', (e) => {
const protocol = require('url').parse(e.url).protocol
if (protocol === 'http:' || protocol === 'https:') {
//shell.openExternal(e.url)
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL(e.url);
}
})
The line shell.openExternal(e.url) open the url of the link in a tab of the default browser.
And by using a new BrowserWindow, the new windows are Electron Window.

Electron Framework - TypeError: Cannot read property 'exec' of undefined

I am new to Electron Framework and I am trying out an application where I need to launch a particular software (e.g. firefox) on a menu item click in my app.
Right now I am trying to build the app on Windows platform (using Windows 7).
Use case
- Home page with static content
- Application menu on top with 'Launch my software' as a menu item
- On click of this menu item I want to launch a software which is installed on my system (I know the path to the exe file)
Steps to create and start the project
npm init (to enter the details of the project and create package.json)
npm install electron --save-dev --verbose
created main.js and main.html (simple HTML file with a header) as mentioned below
npm start
Contents of main.js as follows
const electron = require('electron');
const app = electron.app;
const { Menu } = require('electron');
const BrowserWindow = electron.BrowserWindow;
var childProc = electron.ChildProcess;
var mainWindow;
const menu = Menu.buildFromTemplate([
{
label: 'Menu',
submenu: [{
label: 'Launch my Software',
click: function () {
var child = childProc.exec;
var executablePath = "<path to executable for the software>";
child(executablePath, function(err, data) {
if (err) {
console.error(err);
return;
}
console.log(data.toString());
});
}
}]
}
]);
Menu.setApplicationMenu(menu);
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600
});
mainWindow.loadURL('file://' + __dirname + '/main.html');
mainWindow.setMenu(menu);
mainWindow.on('closed', () => {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('activate', () => {
if (mainWindow == null) {
createWindow();
}
});
After doing npm start, the project is launched. But when I click on the menu item to launch my software, I get the following error
Uncaught Exception:
TypeError: Cannot read property 'exec' of undefined
and it is pointing at line no. 18
var child = childProc.exec;
I went through different posts and tried out the suggestions but it has not worked for me. Can anyone pls help on this.
Thanks in advance.
Electron doesn't have a ChildProcess method or property.
If you want to exec a command then use;
const childProcess = require('child_process')
childProcess.exec('')

Resources