Is the app executed from the Applications folder?
Tldr
It is possible to run an app from its disk image file (e.g. yourapp.dmg
).
Sometimes you want to make sure that users have properly installed the app in their Applications
folder.
Main Process
The renderer process can ask if the app is running from the Applications
folder
by asking in the in-app-folder
IPC channel. The main process will respond in that same channel.
main.js
const {app, BrowserWindow, ipcMain} = require('electron');
const path = require('path');
app.whenReady().then(async () => {
const bwin = new BrowserWindow({
width: 300,
height: 300,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.resolve(__dirname, 'preload.js')
}
});
// Must be registered **before** the renderer process starts.
ipcMain.handle('in-app-folder', () => app.isInApplicationsFolder());
await bwin.loadFile('renderer.html');
bwin.show();
});
Preload Script
The preload script exposes a method under the MY_APP
namespace that
the renderer process can use to know if the app is run from the Applications
folder.
preload.js
const {contextBridge, ipcRenderer} = require('electron');
contextBridge.exposeInMainWorld('MY_APP', {
async isInApplicationsFolder() {
return ipcRenderer.invoke('in-app-folder');
}
});
Renderer Page
The MY_APP
namespace is defined in the preload script and contains
a method to enquire about the app location.
renderer.html
<html>
<head>
<style>
body {background-color:black;color:limegreen}
</style>
</head>
<body>
<h1>Are you running this app from the Applications folder?</h1>
<div id="response"></div>
<script>
MY_APP.isInApplicationsFolder().then(yes => {
if (yes) {
document.querySelector('#response').innerHTML = 'Yes';
} else {
document.querySelector('#response').innerHTML = 'No';
}
});
</script>
</body>
</html>