Cordova Electron app, openFileDialog event - node.js

In my app I open a new window with an external web pagte. This page let users to choose a file. I need to intercept the openFileDialog opened.
Is there a way to do this?
Alternatively ss there a way to execute a script from the external page that runs some function on my electron app?
Thank you
Example:
// open an external page
const { remote } = require('electron');
const { BrowserWindow } = remote;
win = remote.getCurrentWindow();
newWin = new BrowserWindow(
{
parent: win,
modal: false,
show: false,
width: 1280,
height: 1024,
webPreferences: {
nodeIntegration: false,
plugins: true
}
}
);
newWin.loadURL(url);
//Page into newWin will open a file choose dialog and i need to know this is happened...

Did you tried electron dialog, below code snippet uses a same electron thread
const { dialog } = require('electron')
console.log(dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] }))
To exchange information between process you may look into
ipc-main AND webContents

Related

Get path of associated file when opened on double click Electron builder

Information:
OS: windows 10
Electron Version: Latest
Electron Builder Version: Latest
I am trying to make an app that edits .txt files. I want to get the path of the text file when it is opened with the application (i.e. the user chooses to open the .txt with my app). I have included the following in the build of my package.json:
"fileAssociations": [
{
"name": "Text Files",
"description": "Plain Text File",
"ext": [
"txt"
]
}
],
This makes the application open with the file however how do I get the path of the file that was used to open the app. I know I have to do something with a process.argv however I have no idea how to use this. I have tried the below with no success:
ipcMain.on('get-file-data', function(event) {
var data = null;
if (process.platform == 'win32' && process.argv.length >= 2) {
var openFilePath = process.argv[1];
console.log(data)
win.webContents.send('openFile', openFilePath)
}
});
How can I get the path of the file?
This is the log of the whole process. As we can see here, the second argv is the path of the input file path. So process.argv[1] will be enough to the file path. Not sure why you can't get a path.
Maybe this comes from your ipc event listener. Which means the get-file-data is not fired correctly.
As you can see in this below image,I'm showing this process variable in this browser console. Here is how I exposed process variable to the renderer. But this is just for debug! Recommend not doing this in your production.
preload.js
process.once("loaded", () => {
window.process = process;
});
main.js
mainWindow = new BrowserWindow({
width: 1024,
height: 728,
minWidth: 800,
minHeight: 750,
webPreferences: {
enableRemoteModule: true,
preload: path.join(__dirname, "preload.js"),
}
});
And you can use window.process or process on your renderer
I managed to get the path with the following:
const { remote } = require('electron');
console.log(remote.process.argv[1])
This returns the path of the file used to open the app!

Electron - "Cannot read property 'on' of undefined"; tried reinstalling,

I'm testing an electron app but I'm getting this pernicious error:
"TypeError: Cannot read property 'on' of undefined"
The research I've done pointed to either a botched module install, a syntax issue, or passing in an undefined variable to the app.on, and I suspect the issue may be Electron being pointed to incorrectly (now it's being pointed to the folder ending in electron\dist\electron.exe, which I've heard might not the right location), but I'm unsure.
Despite checking the require command, syntax, rechecking, uninstalling, and reinstalling node, I can't seem to make this darn error go away. What could be causing this?
const electron = require('electron');
const os = require('os');
const fs = require('fs');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
var Mousetrap = require('mousetrap');
const path = require('path');
const url = require('url');
const ipc = electron.ipcMain;
let mainWindow;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
/* More code in this and sub functions*/
}))
}
})
const preferencesManager = require('./preferencesManager');
/******
Send data to database given constructor created in preferencesManager
******/
// First instantiate the class because we want to turn the class into an object to be able to use.
const store = new Store({ //create a new getting and setting logic
//We'll call our data file 'user-preferences'
configName: 'user-preferences',
defaults: {
//800 x 600 is the default size of our window
windowBounds: { width: 800, height: 600}
}
});
// When our app is ready, we'll create our BrowserWindow
app.on('ready',function(){
//Set up a listener for what I've done in keycapture (in the renderer process)
//???
ipc.on('invokeAction', function(event, args){
/* Do some action */
});
});
You are probably trying to run your application like a node app with:
$ node index.js
The electron file is a binary file, not a JavaScript file, when you require it an run with node there will be no object to call electron.app, so it parses for null and cannot have an property. As in the getting started documento of Electron.JS you must run the application like this:
Change your package.json script session adding start:
{
"scripts": {
"start": "electron ."
}
}
Now run:
$ npm start
The code you posted has an error, witch may be an edition error while coping and pasting but it should loose some parenthesis and curly brackets:
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
/* More code in this and sub functions*/
}))
}
The application should now run correctly. I tested you exact code, removing the libs I did not have and it loaded with no errors.

Chrome Dev tools in electron app?

I have found that, while running some Electron app, I can access Chrome Dev Tools by pressing Cmd-Alt-I, while on some others I can't. I am wondering which is the setting to avoid/enable this behaviour.
There are a couple of options. You can initialize your BrowserWindow without devtools:
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
devTools: false
}
});
Or you can catch the opened event on the webContents and close it:
mainWindow.webContents.on("devtools-opened", () => {
mainWindow.webContents.closeDevTools();
});

Electron - How to load a html file into the current window?

I was looking all around: docs, google, etc., on how to load a html file in the main window of an electron app, but I can't find a way.
Is it really this complicated or dead simple?
With what I have came up is ajax, thus works:
$("#main").load("./views/details.html");
Another method I have found is via remote:
const {BrowserWindow} = require('electron').remote
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('https://github.com')
But this opens always a new window, and I need to replace the existing page
If you want to load a new URL in an existing window you can do this in the renderer process:
const { remote } = require('electron')
remote.getCurrentWindow().loadURL('https://github.com')
Note that Electron restarts the renderer process when a new URL is loaded, so you'll probably see a flash when that happens. This is why it's usually best to use a single page application (SPA) architecture when building Electron apps.
I know this post is quite old but it's the most popular one on Google in terms of the question of loading new layouts for windows.
I had the same white flash issue because I'm not using any single page framework like React or Vue.js (I'm planning to in the future). So if you are not using too, you can create a function on the main process that hides or shows which window you want to show to make it look like one-page app.
You can get and set each windows' size and position to make the transition better:
function loadPage(page) {
if (page == "landing") {
landingWindow.setSize(uiWindow.getSize()[0],uiWindow.getSize()[1])
landingWindow.setPosition(uiWindow.getPosition()[0],uiWindow.getPosition()[1])
landingWindow.show()
uiWindow.hide()
} else if (page == "main") {
uiWindow.getSize(landingWindow.getSize()[0],landingWindow.getSize()[1])
uiWindow.setPosition(landingWindow.getPosition()[0],landingWindow.getPosition()[1])
uiWindow.show()
landingWindow.hide()
}
exports.loadPage = loadPage;
And you can expose this function to window with a preload script like this:
const electron = require('electron')
const remote = electron.remote
const mainProcess = remote.require('./main')
window.loadPage = mainProcess.loadPage;
Don't forget to initialize both windows on the main process:
function createWindow() {
// Create the browser window.
landingWindow = new BrowserWindow({
width: 1820,
height: 720,
/* fullscreen: true, */
webPreferences: {
nodeIntegration: false,
preload: path.resolve(path.join(__dirname, "preloads/preload.js"))
},
show: false,
backgroundColor: "#222831"
});
landingWindow.loadURL(
url.format({
pathname: path.join(__dirname, "src/landing.html"),
protocol: "file:",
slashes: true
})
);
uiWindow = new BrowserWindow({
width: 1820,
height: 720,
/* fullscreen: true, */
webPreferences: {
nodeIntegration: false,
preload: path.resolve(path.join(__dirname, "preloads/preload.js"))
},
show: false,
backgroundColor: "#222831"
});
uiWindow.loadURL(
url.format({
pathname: path.join(__dirname, "src/mainui.html"),
protocol: "file:",
slashes: true
})
);
// and load the index.html of the app.
// Open the DevTools.
landingWindow.webContents.openDevTools();
// Emitted when the window is closed.
landingWindow.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.
landingWindow = null;
});
landingWindow.once("ready-to-show", () => {
landingWindow.show();
});
}

How can I force external links from browser-window to open in a default browser from Electron?

I'm using the BrowserWindow to display an app and I would like to force the external links to be opened in the default browser. Is that even possible or I have to approach this differently?
I came up with this, after checking the solution from the previous answer.
mainWindow.webContents.on('new-window', function(e, url) {
e.preventDefault();
require('electron').shell.openExternal(url);
});
According to the electron spec, new-window is fired when external links are clicked.
NOTE: Requires that you use target="_blank" on your anchor tags.
new-window is now deprecated in favor of setWindowOpenHandler in Electron 12 (see https://github.com/electron/electron/pull/24517).
So a more up to date answer would be:
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
Improved from the accepted answer ;
the link must be target="_blank" ;
add in background.js(or anywhere you created your window) :
window.webContents.on('new-window', function(e, url) {
// make sure local urls stay in electron perimeter
if('file://' === url.substr(0, 'file://'.length)) {
return;
}
// and open every other protocols on the browser
e.preventDefault();
shell.openExternal(url);
});
Note : To ensure this behavior across all application windows, this code should be run after each window creation.
If you're not using target="_blank" in your anchor elements, this might work for you:
const shell = require('electron').shell;
$(document).on('click', 'a[href^="http"]', function(event) {
event.preventDefault();
shell.openExternal(this.href);
});
I haven't tested this but I assume this is should work:
1) Get WebContents of the your BrowserWindow
var wc = browserWindow.webContents;
2) Register for will-navigate of WebContent and intercept navigation/link clicks:
wc.on('will-navigate', function(e, url) {
/* If url isn't the actual page */
if(url != wc.getURL()) {
e.preventDefault();
openBrowser(url);
}
}
3) Implement openBrowser using child_process. An example for Linux desktops:
var openBrowser(url) {
require('child_process').exec('xdg-open ' + url);
}
let me know if this works for you!
For anybody coming by.
My use case:
I was using SimpleMDE in my app and it's preview mode was opening links in the same window. I wanted all links to open in the default OS browser. I put this snippet, based on the other answers, inside my main.js file. It calls it after it creates the new BrowserWindow instance. My instance is called mainWindow
let wc = mainWindow.webContents
wc.on('will-navigate', function (e, url) {
if (url != wc.getURL()) {
e.preventDefault()
electron.shell.openExternal(url)
}
})
Check whether the requested url is an external link. If yes then use shell.openExternal.
mainWindow.webContents.on('will-navigate', function(e, reqUrl) {
let getHost = url=>require('url').parse(url).host;
let reqHost = getHost(reqUrl);
let isExternal = reqHost && reqHost != getHost(wc.getURL());
if(isExternal) {
e.preventDefault();
electron.shell.openExternal(reqUrl);
}
}
Put this in renderer side js file. It'll open http, https links in user's default browser.
No JQuery attached! no target="_blank" required!
let shell = require('electron').shell
document.addEventListener('click', function (event) {
if (event.target.tagName === 'A' && event.target.href.startsWith('http')) {
event.preventDefault()
shell.openExternal(event.target.href)
}
})
For Electron 5, this is what worked for me:
In main.js (where you create your browser window), include 'shell' in your main require statement (usually at the top of the file), e.g.:
// Modules to control application life and create native browser window
const {
BrowserWindow,
shell
} = require('electron');
Inside the createWindow() function, after mainWindow = new BrowserWindow({ ... }), add these lines:
mainWindow.webContents.on('new-window', function(e, url) {
e.preventDefault();
shell.openExternal(url);
});
I solved the problem by the following step
Add shell on const {app, BrowserWindow} = require('electron')
const {app, BrowserWindow, shell} = require('electron')
Set nativeWindowOpen is true
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 1350,
height: 880,
webPreferences: {
nativeWindowOpen: true,
preload: path.join(__dirname, 'preload.js')
},
icon: path.join(__dirname, './img/icon.icns')
})
Add the following listener code
mainWindow.webContents.on('will-navigate', function(e, reqUrl) {
let getHost = url=>require('url').parse(url).host;
let reqHost = getHost(reqUrl);
let isExternal = reqHost && reqHost !== getHost(wc.getURL());
if(isExternal) {
e.preventDefault();
shell.openExternal(reqUrl, {});
}
})
reference https://stackoverflow.com/a/42570770/7458156 by cuixiping
I tend to use these lines in external .js script:
let ele = document.createElement("a");
let url = "https://google.com";
ele.setAttribute("href", url);
ele.setAttribute("onclick", "require('electron').shell.openExternal('" + url + "')");

Resources