Would I be able to give access to specific electron APIs safely? - javascript

So I need to find a way to create custom window titleBar buttons that I can add functionality to safely without enabling nodeIntegration in electron. I was thinking the preload might be what I need but I'm not sure how this works or if it would work for this.
Since I'm creating custom window buttons with HTML, CSS and Javascript, I need these methods:
mainWindow.minimize();
mainWindow.close();
mainWindow.getBounds();
mainWindow.setBounds(...);
mainWindow.setResizable(...);
This is in the renderer process so nodeIntegration would need to be enabled and would need to use remote like this:
const { remote } = require('electron');
const mainWindow = remote.getCurrentWindow();
Would I be able to use the preload option with nodeIntegration disabled to access these methods to add functionality to my custom buttons? If so, how? Would it be safe this way?

You could add a preload script which provides some APIs, just like the following one:
const { remote } = require("electron");
function initialise () {
window.Controls = {
minimize: () => { remote.getCurrentWindow ().minimize (); },
close: () => { remote.getCurrentWindow ().close (); },
getBounds: () => { remote.getCurrentWindow ().getBounds (); },
setBounds: (bounds) => { remote.getCurrentWindow ().setBounds (bounds); },
setResizable: (resizable) => { remote.getCurrentWindow ().setResizable (resizeable); }
};
}
initialise ();
Then, you can use the functions defined like this in your renderer process:
document.getElementById ("close-button").addEventListener ("click", (e) => {
window.Controls.close ();
});
This reduces the risk of executing insecure code by just setting nodeIntegration: true on the BrowserWindow. However, all code which has access to window.Controls will be able to manipulate the window state.

Related

Leaflet geoman "Button with this name already exists" error when creating a new button in react

I am trying to create a custom button for arrows in the drawing tool of leaflet-geoman.
The idea was to work with the copyDrawControl function, and to use Line as a model to make Polylines with arrow tips.
I wrote a code mostly inspired from this demonstration https://codesandbox.io/s/394eq?file=/src/index.js and modified it for my goals. Here is the code :
import { useEffect } from "react";
import { useLeafletContext } from "#react-leaflet/core";
import "#geoman-io/leaflet-geoman-free";
import "#geoman-io/leaflet-geoman-free/dist/leaflet-geoman.css";
const Geoman = () => {
const context = useLeafletContext();
useEffect(() => {
const leafletContainer = context.layerContainer || context.map;
leafletContainer.pm.setGlobalOptions({ pmIgnore: false });
//draw control options
leafletContainer.pm.addControls({
positions: {
draw: 'topleft',
edit: 'topright',
},
drawMarker: false,
rotateMode: false,
cutPolygon: false,
position: "bottomright"
});
//new button
leafletContainer.pm.Toolbar.copyDrawControl('Line', {
name: 'SoonToBeArrow',
block: 'draw',
title: 'Display text on hover button',
actions: [
// uses the default 'cancel' action
'cancel',
],
});
return () => {
leafletContainer.pm.removeControls();
leafletContainer.pm.setGlobalOptions({ pmIgnore: true });
};
}, [context]);
return null;
};
export default Geoman;
When trying to add the copyDrawControl, I faced a bug that would announce that "Button with this name already exists"
I suspect its because I add the button inside a useEffect that gets called several times, but it's also the only way to access leafletContainer, since it must be updated everytime the context changes.
I tried creating another useEffect that contains the same context and my new button, but it did not work.
Does anyone have any suggestion on how to solve this ?
Thnak you in advance
You only want to run this effect once, just after context becomes available. In order to do this, we can make a state variable to track whether or not you've already added the control:
const Geoman = () => {
const context = useLeafletContext();
const [added, setAdded] = useState(false);
useEffect(() => {
const leafletContainer = context.layerContainer || context.map;
// if the context is ready, and we've not yet added the control
if (leafletContainer && !added){
leafletContainer.pm.setGlobalOptions({ pmIgnore: false });
//draw control options
leafletContainer.pm.addControls({
// ...
});
//new button
leafletContainer.pm.Toolbar.copyDrawControl('Line', {
// ...
});
// register that we've already added the control
setAdded(true);
}
return () => {
leafletContainer.pm.removeControls();
leafletContainer.pm.setGlobalOptions({ pmIgnore: true });
};
}, [context]);
return null;
};
In this way, you effect will run whenever context changes - once context is ready, you add the control. You register that you've added the control, but then your if statement will make sure that further changes in context will not try to keep adding controls again and again.
BTW, a second option to using leaflet geoman with react leaflet is to use the official createControlComponent hook to create custom controls. This is not at all straightforward with leaflet-geoman, as createControlComponent requires you to feed it an instance of an L.Control that has all the required hooks and initializer methods. geoman does not have these - it is quite different in the way it initializes and adds to a map. However, you can create an L.Control from geoman methods, and then feed it to createControlComponent.
Create the L.Control:
/**
* Class abstraction wrapper around geoman, so that we can create an instance
* that is an extension of L.Control, so that react-leaflet can call all
* L.PM methods using the expected L.Control lifecycle event handlers
*/
const GeomanControl = L.Control.extend({
initialize(options: Props) {
L.PM.setOptIn(options.optIn ?? false);
L.setOptions(this, options);
},
addTo(map: L.Map) {
const { globalOptions, events } = this.options;
// This should never happen, but its better than crashing the page
if (!map.pm) return;
map.pm.addControls(toolbarOptions);
map.pm.setGlobalOptions({
pmIgnore: false,
...globalOptions,
});
// draw control options
map.pm.addControls({
// ...
});
// new button
map.pm.Toolbar.copyDrawControl('Line', {
// ...
});
Object.entries(events ?? {}).forEach(([eventName, handler]) => {
map.on(eventName, handler);
});
},
});
Then simply use createControlComponent
const createControl = (props) => {
return new GeomanControl(props);
};
export const Geoman = createControlComponent(createControl);
You can add quite a lot of logic into the addTo method, and base a lot of its behaviors off the props you feed to <Geoman />. This is another flexible way of adapting geoman for react-leaflet v4.

Is there a way to let the program remember which URL was open when the user closed the program?

Is there a way to let the program remember which URL was open when the user closed the program? For example if the user closes the application, the last URL gets added to the loadURL. The program is being used for users that only can interact with touchscreen and cant leave the specific site. I am using windows 10 and the newest version of electron.
// Modules to control application life and create native browser window.
const { app, BrowserWindow, Menu } = 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 mainWindow;
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
frame: false,
webPreferences: {
preload: `${__dirname}/preload.js`
}
});
// The loadURL that loads if you start up the application.
mainWindow.loadURL("https://google.com");
// 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;
});
}
// The toggleFullScreen function stated in the createMainMenu function.
function toggleFullscreen() {
if (mainWindow.isFullScreen()) {
mainWindow.setFullScreen(false);
} else {
mainWindow.setFullScreen(true);
}
}
function createMainMenu() {
const template = [
{
label: "Options",
submenu:
[
{
label: "Quit",
accelerator: "CmdOrCtrl+Q",
click() {
app.quit();
}
},
{
label: 'Toggle full screen',
accelerator: 'CmdOrCtrl+F',
click: () => {
toggleFullscreen();
}
},
{
label: 'Toggle developer tools',
accelerator: 'CmdOrCtrl+I',
click(item, focusedWindow){
focusedWindow.toggleDevTools();
}
}
]
}
];
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
}
// 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();
createMainMenu();
});
// Quit when all windows are closed.
app.on("window-all-closed", function() {
// 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", function() {
// 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();
}
});
// 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.
You have two options.
First, each time the URL changes, use LocalStorage in the renderer process. It will work just like in a web app.
Second, each the URL changes, have it send a message back to the main process, and have it write that to a local file. getPath('appData') can be used to get the OS-specific directory of where settings files can be written.

"Uncaught ReferenceError: window is not defined" p5.js web worker

I have a javascript code where I use the web worker with the p5.js library. it wouldn't allow me to use any of p5's functions so I have to use the importScripts("p5.js") function to import the p5.js library before using any of p5's functions.
onmessage = (e)=>{
importScripts("p5.min.js")
// other scripts
}
But even then it gives me another error that said "Uncaught ReferenceError: window is not defined". I tracked it down and it seemed that p5 is unable to use the global variable named "window". I searched around the internet for a solution but so far found none. I wonder if there is a way around this. Thank you.
The issue here is that web workers run in a very isolated context where many of the standard global variables that would exist for javascript running on a website (window, document, etc) don't exist, and unfortunately p5.js cannot load without these variables. You could try shimming them with fake versions. Here's a basic example:
let loadHandlers = [];
window = {
performance: performance,
document: {
hasFocus: () => true,
createElementNS: (ns, elem) => {
console.warn(`p5.js tryied to created a DOM element '${ns}:${elem}`);
// Web Workers don't have a DOM
return {};
}
},
screen: {},
addEventListener: (e, handler) => {
if (e === "load") {
loadHandlers.push(handler);
} else {
console.warn(`p5.js tried to added an event listener for '${e}'`);
}
},
removeEventListener: () => {},
location: {
href: "about:blank",
origin: "null",
protocol: "about:",
host: "",
hostname: "",
port: "",
pathname: "blank",
search: "",
hash: ""
}
};
document = window.document;
screen = window.screen;
// Without a setup function p5.js will not declare global functions
window.setup = () => {
window.noCanvas();
window.noLoop();
};
importScripts("/p5.js");
// Initialize p5.js
for (const handler of loadHandlers) {
handler();
}
postMessage({ color: "green" });
onmessage = msg => {
if (msg.data === "getRandomColor") {
// p5.js places all of its global declarations on window
postMessage({
color: window.random([
"red",
"limegreen",
"blue",
"magenta",
"yellow",
"cyan"
])
});
}
};
This is only going to work for a limited subset of p5.js functions. Any functions that draw to the canvas are definitely not going to work. And I would be cautious about trying to pass objects back and forth (i.e. p5.Vector, p5.Color, etc) because everything sent via postMessage gets serialized and deserialized.
I've posted a working version of this example on Glitch.

Electron "require is not defined"

I'm making an application which I need to give access to the file system (fs) module, however even with nodeIntegration enabled the renderer gives me this error:
Uncaught ReferenceError: require is not defined
All similar problems I could find had a solution that said they needed to turn nodeIntegration on, however I already have it enabled.
This is my main.js:
const electron = require('electron');
const {app, BrowserWindow} = electron;
let win;
app.on('ready', () => {
var { width, height } = electron.screen.getPrimaryDisplay().workAreaSize;
width = 1600;
height = 900;
win = new BrowserWindow({'minHeight': 850, 'minWidth': 1600, width, height, webPreferences: {
contextIsolation: true,
webSecurity: true,
nodeIntegration: true
}});
win.setMenu(null);
win.loadFile('index.html');
win.webContents.openDevTools()
});
My index.js, linked in index.html as <script src="index.js"></script> currently only has require("fs"); in it, I've commented out all the other stuff.
I don't know why require still doesn't work even though nodeIntegration is enabled.
When you have nodeIntegration disabled but aren't using contextIsolation, you could use a preload script to expose a safe version of it on the global object. (Note: you shouldn't expose the entire fs module to a remote page!)
Here's an example of using a preload script in this way:
// main process script
const mainWindow = new BrowserWindow({
webPreferences: {
contextIsolation: false,
nodeIntegration: false,
preload: './preload.js'
}
})
mainWindow.loadURL('my-safe-file.html')
// preload.js
const { readFileSync } = require('fs')
// the host page will have access to `window.readConfig`,
// but not direct access to `readFileSync`
window.readConfig = function () {
const data = readFileSync('./config.json')
return data
}
// renderer.js
const config = window.readConfig()
If you're only loading local pages, and those pages don't load or execute unsafe dynamic content then you might reconsider the use of contextIsolation for this strategy. If you want to keep contextIsolation on, however (and you definitely should if you have a chance of showing unsafe content), you can only communicate with the preload script with message passing via postMessage.
Here's an example of the same scenario above, but with contextIsolation on and using message passing.
// main process script
const mainWindow = new BrowserWindow({
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: './preload.js'
}
})
mainWindow.loadURL('my-unsafe-file.html')
// preload.js
const { readFileSync } = require('fs')
const readConfig = function () {
const data = readFileSync('./config.json')
return data
}
window.addEventListener('message', (event) => {
if (event.source !== window) return
if (event.data.type === 'request') {
window.postMessage({ type: 'response', content: readConfig() })
}
})
// renderer.js
window.addEventListener('message', (event) => {
if (event.source !== window) return
if (event.data.type === 'response') {
const config = event.data.content
}
})
window.postMessage('request')
While this is definitely more verbose and difficult to deal with (and forces things to be async, because message passing is async), it's also much more secure. A pair of small JS wrappers around the postMessage API could make this easier to work with (e.g. via an RPC-like mechanism), but remember that the whole point of using contextIsolation is because you can't trust the renderer, so your preload script shouldn't trust just any message it gets via the postMessage API — you should always verify the event that you receive to ensure that you trust it.
This slide deck describers in detail why turning off Node integration without using context isolation is not always a good idea.

Electron global shortcut to toggle show/hide of menubar

I am trying to add a global shortcut to my Electron app that will toggle showing/hiding it. My app is a menubar app built using maxogden/menubar and React.
I have the following code. I've left a couple of bits out just for brevity but this is how I have setup the global shortcuts.
I think it's important to note one of the tips on the maxogden/menubar Readme too:
Use mb.on('after-create-window', callback) to run things after your
app has loaded
const { globalShortcut } = require('electron');
const keyboardShortcuts = {
open: 'CommandOrControl+Shift+g',
close: 'CommandOrControl+Shift+g'
}
menu.on('after-create-window', () => {
globalShortcut.register(keyboardShortcuts.open, () => {
menu.window.show();
});
});
menu.on('after-show', () => {
globalShortcut.unregister(keyboardShortcuts.open);
globalShortcut.register(keyboardShortcuts.close, () => {
menu.window.hide();
});
});
menu.on('focus-lost', () => {
globalShortcut.unregister(keyboardShortcuts.close);
globalShortcut.register(keyboardShortcuts.open, () => {
menu.window.show();
});
});
Once the menubar has first been opened, my shortcut is registered and will work to show the app. However, the code I've implemented to unregister the shortcut, and re-register it to hide the app (when showing), doesn't seem to work.
I'm not sure if my code to reregister the shortcut is setup within the right event handler i.e after-show and focus-lost. I have a feeling that these event handlers I'm working within are related directly to my menu rather than menu.window. This would explain why the reregistration of the shortcut isn't happening, but I'm not sure.
Does anyone have any idea how I would sensibly set up a global shortcut toggle to open/close my menubar app?
From the menubar docs (https://github.com/maxogden/menubar) the menubar instance exposes the following methods:
{
app: the electron require('app') instance,
window: the electron require('browser-window') instance,
tray: the electron require('tray') instance,
positioner: the electron-positioner instance,
setOption(option, value): change an option after menubar is created,
getOption(option): get an menubar option,
showWindow(): show the menubar window,
hideWindow(): hide the menubar window
}
Using menu.showWindow() & menu.hideWindow() instead of menu.window.show() & menu.window.hide() will work.
I would further suggest that you use the built in events to manage your state, simplifying your code and implementation:
const { globalShortcut } = require('electron');
let isShown = false;
menu
.on('after-show', () => { isShown = true })
.on('after-hide', () => { isShown = false })
.on('focus-lost', () => { isShown = false });
globalShortcut.register('CommandOrControl+Shift+g', () => {
isShown ? menu.hideWindow() : menu.showWindow()
});

Categories

Resources