I have been reading through the electron security documentation. https://electronjs.org/docs/tutorial/security trying to understand how I should write my code securely.
From my understanding, I should use the webPreferences and preload script to access features that will access the file system.
I want to have a button that opens a file picker.
I have tried using the preload script but as far as I can tell the script never loads or runs. Can someone explain to me how the preload script works? Where does it load or where can I look in the chrome dev tools to check it has loaded? When does it run, before the page loads or after? Can I still reference funtions in the script from the html file?
const mainWindow = new BrowserWindow({
{width: 800, height: 600},
webPreferences: {
nodeIntegration: false,
preload: `file://${__dirname}/index.js`
}
});
mainWindow.loadURL(`file://${__dirname}/index.html`);
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Electron Hello World!</title>
</head>
<body>
<h1>Electron Hello World!</h1>
We are using node <script>document.write(process.versions.node)</script>,
Chromium <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
<br/>
<button id="openFile" onclick="openFile();">Open</button>
<br />
<textarea id="editor" style="width: 400px; height: 300px;"></textarea>
</body>
</html>
index.ts
{
console.log('preloaded');
const electron = require('electron').remote;
const dialog = electron.dialog;
const fs = require('fs');
function openFile () {
dialog.showOpenDialog({filters: [{ name: 'text', extensions: ['txt'] }]}, function (fileNames) {
if (fileNames === undefined)
{
return;
}
var fileName = fileNames[0];
fs.readFile(fileName, 'utf-8', function (err, data) {
document.getElementById("editor").innerText = data;
});
});
}
}
This code doesn't work. The versions number from the index.html don't display but causes errors in the console. The console.log doesn't run and the button event doesn't work.