Open my Electron App from a webpage using a registered protocol - javascript

I am using app.setAsDefaultProtocolClient("bithop"); but when I navigate to bithop:// in my browser, I just get the default electron app. (Where it says "To run a local app...")
This is not packaged as a .asar app. The documentation on this seems to be very unclear.
app.setAsDefaultProtocolClient("bithop");
(This is the last line of app.js)
When I go to bithop:// from a web browser, it should open my electron app.
This is the entire script:
const {app, BrowserWindow} = require('electron');
let window;
function createWindow() {
window = new BrowserWindow({
width: 800,
height: 600,
frame: false
});
window.loadFile('pages/index.html');
//window.openDevTools();
window.on('closed', function () {
window = null;
});
};
app.on('ready', createWindow)
app.on('window-all-closed', app.quit)
//Register Protocol
app.setAsDefaultProtocolClient("bithop");

I found that I needed to download the electron binaries, and put my app inside it, instead of installing as an npm module. I used https://github.com/electron-userland/electron-packager, which was really simple.

Related

Uncaught ReferenceError: require is not defined - Electron js

I'm using electron for the first time at the same time as js and node, I'm trying to make an application for hobby and knowledge.
I'm facing a problem when implementing my script to open external links.
I've been using the doc to fix the problem, but I haven't seen anything to help me with that problem.
My ex-links.js
const electron = require("electron");
const { shell } = electron;
const exLinkBtn = document.getElementById("open-ex-link");
exLinkBtn.addEventListener("click", function() {
shell.openExternal("https://www.youtube.com/watch?v=ifXalt3MJtM");
});
I've already tried to place the slider.html inside index.html and yet I still get that error, so I left it as I currently have it inside an iframe.
<iframe src="slider.html" frameborder=0 width="1180" height="728" style="padding-left:198.5px;"></iframe>
I expect that by clicking the open-ex-link button it will open the link in the default browser.
The default nodeIntegration value is false. So you can set it to true to solve the issue.
app.on('ready', () => {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
});
But, nodeIntegration: true is a security risk when you are executing some untrusted remote code on your application. For example, when your application opens up a third party webpage, it would be a security risk because the third party webpage will have access to node runtime and can run malicious code on the user's filesystem. So it makes sense to set nodeIntegration: false which is the default now.
You can use preload scripts as they have access to require and other Node.js features.
The index.js would be like:
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(app.getAppPath(), 'preload.js')
}
})
The preload.js would be like:
const { remote } = require('electron');
let currentWindow = remote.BrowserWindow.getFocusedWindow();
window.closeCurrentWindow = function(){
currentWindow.close();
}

Convert Angular Framework Application to desktop application using Electron

Project Description:
I have a functional front-end angularjs application that communicates with another back-end Java application deployed in tomcat running on different port(8443). I have been running it on a web browser but now i want to run it as a desktop application. I have been running it as grunt serve for development environment and grunt --clean --prod for production and distribution.
When run in dev mode using grunt serve, the application runs on http://localhost:9000/?baseApiUrl=https://localhost:8443&tenantIdentifier=demo
Question:
How do i go about making the application run in electron for dev mode and later package it for production? I tried How to port an existing angular app to electron? but it can't communication with the backed application on the port.
Please help.
Here's how,
1. The boilerplate code.
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
let mainWindow = null;
function createWindow () {
mainWindow = new BrowserWindow({width: 800, height: 600});
mainWindow.loadURL(`file://${__dirname}/index.html`);
//Take note of this line.
//mainWindow.loadURL(`http://localhost:9000`);
mainWindow.on('closed', function () {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow();
}
});
2. Take note of the line mainWindow.loadURL('file://${__dirname}/index.html'). Since your use case is to communicate with another backend application running on a port, using the file protocol (file://<uri>) won't work, you need to communicate with the port on http protocol.
3. To achieve this, I suggest to run a static files http server in your electron application, server your app over local server, and replace this mainWindow.loadURL('file://${__dirname}/index.html') line with mainWindow.loadURL(`http://localhost:9000`) this.
Edit 1:
You can run a very basic static files server like so, however there certainly are better ways to write it.
var express = require('express');
var server = express();
server.use('/', express.static(__dirname + '/'));
server.listen(9000);
Edit 2:
After some discussion in the comments, I decided to clone the repo and add the electron part myself, here's how I did it.
1. Install the following dependencies by running,
npm install --save electron express
2. index.js file
const electron = require('electron');
const path = require('path');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
let mainWindow = null;
var express = require('express');
var server = express();
let dir = path.join(__dirname, './dist/community-app');
server.use('/', express.static(dir));
server.listen(9000);
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600
});
mainWindow.loadURL(`http://localhost:9000`);
mainWindow.on('closed', function () {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow();
}
});
3. Add the following script in your package.json
"scripts": {
//...
"start": "electron ."
},
4. Result
PS: I had some troubles building angularjs project, because there were no build scripts in the project for windows, hence some styles are missing from the page.
Git repo:
https://github.com/openMF/community-app

Electron require() is not defined

I'm creating an Electron app for my own purpose. My problem is when I'm using node functions inside my HTML page it throws an error of:
'require()' is not defined.
Is there any way to use Node functionalities in all my HTML pages? If it is possible please give me an example of how to do this or provide a link. Here are the variables I'm trying to use in my HTML page:
var app = require('electron').remote;
var dialog = app.dialog;
var fs = require('fs');
and these are the values I'm using in all my HTML windows within Electron.
As of version 5, the default for nodeIntegration changed from true to false.
You can enable it when creating the Browser Window:
app.on('ready', () => {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
});
});
Edit 2022
I've published a larger post on the history of Electron and it's security that provides additional context on the changes that affect how security was approached in different framework versions (and what's the best approach to take).
Original answer
I hope this answer gets some attention, because a large majority of answers here leave large security holes in your electron app. In fact this answer is essentially what you should be doing to use require() in your electron apps. (There is just a new electron API that makes it a little bit cleaner in v7).
I wrote a detailed explanation/solution in github using the most current electron apis of how you can require() something, but I'll explain briefly here why you should follow an approach using a preload script, contextBridge and ipc.
The problem
Electron apps are great because we get to use node, but this power is a double-edged sword. If we are not careful, we give someone access to node through our app, and with node a bad actor can corrupt your machine or delete your operating system files (among other things, I imagine).
As brought up by #raddevus in a comment, this is necessary when loading remote content. If your electron app is entirely offline/local, then you are probably okay simply turning on nodeIntegration:true. I still would, however, opt to keep nodeIntegration:false to act as a safeguard for accidental/malicious users using your app, and prevent any possible malware that might ever get installed on your machine from interacting with your electron app and using the nodeIntegration:true attack vector (incredibly rare, but could happen)!
What does the problem look like
This problem manifests when you (any one of the below):
Have nodeIntegration:true enabled
Use the remote module
All of these problems give uninterrupted access to node from your renderer process. If your renderer process is ever hijacked, you can consider all is lost.
What our solution is
The solution is to not give the renderer direct access to node (ie. require()), but to give our electron main process access to require, and anytime our renderer process needs to use require, marshal a request to the main process.
The way this works in the latest versions (7+) of Electron is on the renderer side we set up ipcRenderer bindings, and on the main side we set up ipcMain bindings. In the ipcMain bindings we set up listener methods that use modules we require(). This is fine and well because our main process can require all it wants.
We use the contextBridge to pass the ipcRenderer bindings to our app code (to use), and so when our app needs to use the required modules in main, it sends a message via IPC (inter-process-communication) and the main process runs some code, and we then send a message back with our result.
Roughly, here's what you want to do.
main.js
const {
app,
BrowserWindow,
ipcMain
} = require("electron");
const path = require("path");
const fs = require("fs");
// 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;
async function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false, // is default value after Electron v5
contextIsolation: true, // protect against prototype pollution
enableRemoteModule: false, // turn off remote
preload: path.join(__dirname, "preload.js") // use a preload script
}
});
// Load app
win.loadFile(path.join(__dirname, "dist/index.html"));
// rest of code..
}
app.on("ready", createWindow);
ipcMain.on("toMain", (event, args) => {
fs.readFile("path/to/file", (error, data) => {
// Do something with file contents
// Send result back to renderer process
win.webContents.send("fromMain", responseObj);
});
});
preload.js
const {
contextBridge,
ipcRenderer
} = require("electron");
// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
// whitelist channels
let validChannels = ["toMain"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["fromMain"];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
}
}
);
index.html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8"/>
<title>Title</title>
</head>
<body>
<script>
window.api.receive("fromMain", (data) => {
console.log(`Received ${data} from main process`);
});
window.api.send("toMain", "some data");
</script>
</body>
</html>
Disclaimer
I'm the author of secure-electron-template, a secure template to build electron apps. I care about this topic, and have been working on this for a few weeks (at this point in time).
For security reasons, you should keep nodeIntegration: false and use a preload script to expose just what you need from Node/Electron API to the renderer process (view) via window variable. From the Electron docs:
Preload scripts continue to have access to require and other Node.js features
Example
main.js
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(app.getAppPath(), 'preload.js')
}
})
preload.js
const { remote } = require('electron');
let currWindow = remote.BrowserWindow.getFocusedWindow();
window.closeCurrentWindow = function(){
currWindow.close();
}
renderer.js
let closebtn = document.getElementById('closebtn');
closebtn.addEventListener('click', (e) => {
e.preventDefault();
window.closeCurrentWindow();
});
First off, #Sathiraumesh solution leaves your electron application with huge security issue. Imagine that your app is adding some extra features to messenger.com, for example toolbar's icon will change or blink when you've have unread message. So in your main.js file, you create new BrowserWindow like so (notice I intentionally misspelled messenger.com):
app.on('ready', () => {
const mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadURL(`https://messengre.com`);
});
What if messengre.com is a malicious website, that wants to harm your computer. If you set nodeIntegration: true this site has access to your local file system and can execute this:
require('child_process').exec('rm -r ~/');
And your home directory is gone.
Solution
Expose only what you need, instead of everything. This is achived by preloading javascript code with require statements.
// main.js
app.on('ready', () => {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: `${__dirname}/preload.js`
}
});
mainWindow.loadURL(`https://messengre.com`);
});
// preload.js
window.ipcRenderer = require('electron').ipcRenderer;
// index.html
<script>
window.ipcRenderer.send('channel', data);
</script>
Now awful messengre.com cannot delete your entire file system.
It looks like Electron's security evolved like this (source).
Electron 1 nodeIntegration defaults to true
Renderer has full access to Node API -- huge security risks if Renderer loads remote code.
Electron 5 nodeIntegration defaults to false
When set to false, a preload script is used to expose specific API to Renderer. (The preload script always has access to Node APIs regardless of the value of nodeIntegration)
//preload.js
window.api = {
deleteFile: f => require('fs').unlink(f)
}
Electron 5 contextIsolation defaults to true (actually still defaults to false in Electron 11)
This causes preload script to run in a separate context. You can no longer do window.api = .... You now have to do:
//preload.js
const { contextBridge } = require('electron')
contextBridge.exposeInMainWorld('api', {
deleteFile: f => require('fs').unlink(f)
})
Electron 6 require()ing node builtins in sandboxed renderers no longer implicitly loads the remote version
If Renderer has sandbox set to true, you have to do:
//preload.js
const { contextBridge, remote } = require('electron')
contextBridge.exposeInMainWorld('api', {
deleteFile: f => remote.require('fs').unlink(f)
})
Electron 10 enableRemoteModule default to false (remote module deprecated in Electron 12)
The remote module is used when you need to access Node APIs from a sandboxed Renderer (as in above example); or when you need to access Electron APIs that are available only to the Main process (such as dialog, menu). Without remote, you'll need to write explicit IPC handlers like follows.
//preload.js
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('api', {
displayMessage: text => ipcRenderer.invoke("displayMessage", text)
})
//main.js
const { ipcMain, dialog } = require('electron')
ipcMain.handle("displayMessage", text => dialog.showMessageBox(text))
Electron 10 deprecate nodeIntegration flag (removed in Electron 12)
Recommendation
Always set {nodeIntegration: false, contextIsolation: true, enableRemoteModule: false}.
For max security, set {sandbox: true}. Your preload script will have to use IPC to call the Main process to do everything.
If sandbox is false, your preload script can access Node API directly, as in require('fs').readFile. You're secure as long as you don't this:
//bad
contextBridge.exposeInMainWorld('api', {
readFile: require('fs').readFile
})
Are you using nodeIntegration: false while BrowserWindow initialization? If so, set it to true (defaults value is true).
And include your external scripts in the HTML like this (not as <script> src="./index.js" </script>):
<script>
require('./index.js')
</script>
All I wanted to do was to require a js file in my html page because of the tutorial I was following. However, I intend to use remote modules so security was paramount. I modified Michael's answer up there so I'm posting, purely for those who spent hours looking for a secure alternative to 'require' like me. If the code is incorrect, feel free to point it out.
main.js
const electron = require('electron');
const app=electron.app;
const BrowserWindow=electron.BrowserWindow;
const ipcMain=electron.ipcMain;
const path=require('path');
const url=require('url');
let win;
function createWindow(){
win=new BrowserWindow({
webPreferences:{
contextIsolation: true,
preload: path.join(__dirname, "preload.js")
}
});
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file',
slashes: true
}));
win.on('close', function(){
win=null
});
}
app.on('ready', createWindow);
preload.js
const electron=require('electron');
const contextBridge=electron.contextBridge;
contextBridge.exposeInMainWorld(
"api", {
loadscript(filename){
require(filename);
}
}
);
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello World App</title>
</head>
<body>
<h1>Hello World</h1>
<button id="btn">Click</button>
</body>
<script>
window.api.loadscript('./index.js');
</script>
</html>
index.js
const btn = document.getElementById('btn');
btn.addEventListener('click', function(){
console.log('button clicked');
});
I am especially curious to know if this still presents a security risk. Thanks.
If you just don't care about any security issues and want to have require being interpreted correctly by JavaScript on the browser window, then have an extra flag on the main.js code:
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
nodeIntegrationInSubFrames: true,
enableRemoteModule: true,
contextIsolation: false //required flag
}
//rest of the code...
You have to enable the nodeIntegration in webPreferences to use it. see below,
const { BrowserWindow } = require('electron')
let win = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
})
win.show()
There was a breaking api changes in electron 5.0(Announcement on Repository). In recent versions nodeIntegration is by default set to false.
Docs Due to the Node.js integration of Electron, there are some extra symbols inserted into the DOM like module, exports, require. This causes problems for some libraries since they want to insert the symbols with the same names.To solve this, you can turn off node integration in Electron:
But if you want to keep the abilities to use Node.js and Electron APIs, you have to rename the symbols in the page before including other libraries:
<head>
<script>
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
</script>
<script type="text/javascript" src="jquery.js"></script>
</head>
For sake of actuality and completeness I am adding my piece of cake. Here is what I find important about this topic. Please keep in mind the date of this post - October 2022, the version of electron is 21.1.1.
There is an article in electron docs called Inter-Process Communication where this topic is described in a very clear way.
The following code is just a copy of the example code on that aforementioned site.
The main.js file:
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
function createWindow () {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
ipcMain.on('set-title', (event, title) => {
const webContents = event.sender
const win = BrowserWindow.fromWebContents(webContents)
win.setTitle(title)
})
mainWindow.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
The takeaway:
in webPreferences define only the preload script and leave all those nodeIntegration, nodeIntegrationInWorker, nodeIntegrationInSubFrames, enableRemoteModule, contextIsolation apply the defaults.
The next file is preload.js:
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
setTitle: (title) => ipcRenderer.send('set-title', title)
})
Here the electronAPI object will be injected into the browsers context so there will be a window.electronAPI object which will have a member function called setTitle. Of course you can add whatever other properties there.
The setTitle function only calls ipcRenderer.send which is one end of the Inter-Process Communication brigde or tunnel if you like.
What you send in here falls out on the other end, which is in the main.js file, the ipcMain.on function. Here you register for the set-title event.
The example continues with the index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Hello World!</title>
</head>
<body>
Title: <input id="title"/>
<button id="btn" type="button">Set</button>
<script src="./renderer.js"></script>
</body>
</html>
which loads the renderer.js script:
const setButton = document.getElementById('btn')
const titleInput = document.getElementById('title')
setButton.addEventListener('click', () => {
const title = titleInput.value
window.electronAPI.setTitle(title)
});
and there you can access the window.electronAPI.setTitle function, which you defined in preload.js where it sends the title into ipcRenderer and this title then falls out of ipcMain in main.js fireing an event and causing a function to run which in turn sets the application title.
So once again I want to emphasize to read the documentation. There is more about IPC with exanples. Also read the Context Isolation chapter, it is short and very clear.
Finally, I made it work.Add this code to your HTML document Script Element.
Sorry for the late Reply.I use the below code to do this thing.
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
And use nodeRequire instead of using require.
It works Fine.

Electron missing node_modules

So, im migrating my Angular2 WebApp into electron, I so far so good, i made the electron run the app with the electron command, but when I build the app there are some modules missing, like systemjs, and zonejs.
how can I include all node_modules on the build??
this is my index.js file (the electron config)
const {app, BrowserWindow} = 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 win
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 1200, height: 800, "node-integration": false})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: false
}))
// Open the DevTools.
win.webContents.openDevTools()
// 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.

Electron app isn't working properly

I wanted to convert quite simple web app to a desktop app with electron. But there is one big problem. The app, that I want to convert is here: dinoz.mobi/shelter-editor
So as you can see there is a page that tells us to load a file.
When I converted it to desktop app, it looks like this: screen
This is my package.json file:
{
"name" : "Editor",
"version" : "0.1.0",
"main" : "main.js"
}
And main.js file:
const {app, BrowserWindow} = require('electron')
// 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: 1366, height: 768})
webPreferences: {
nodeIntegration: false
}
win.show()
// and load the index.html of the app.
win.loadURL(`file://${__dirname}/shelter.html`)
// 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.
And here is link to app's github page: https://github.com/MobileSam/shelter-editor
What is wrong with it?
Ok, repaired by adding this script <script>window.jQuery = window.$ = module.exports</script>
after a <script src="js/jquery-2.1.4.min.js"></script>

Categories

Resources