I just started playing with electron and as a playground I opted to draft a raw basic javascript console.
The code is entered on a <textarea> and once a button is pushed the code gets executed with webContent.executeJavaScript and the result is shown in an output <div/>. Clearly enough I would also like to show as output any eventual error message.
Not being able to find in the electron documentation a clear way to do it I came up with a solution (below reduced to the bare minimum) which does not really make me happy:
// main.js
ipcMain.handle('runjs', (event, code ) =>
mainWindow.webContents.executeJavaScript(code, true)
);
// preload.js
const { ipcRenderer, contextBridge } = require('electron');
contextBridge.exposeInMainWorld('api', {
runjs: code => ipcRenderer.invoke('runjs', code),
});
// triggering component
import React from 'react'
export default ({code}) => {
const onClick = () => window.api.runjs(`
(() => {
try {
var t = eval('${code.replace(/\n|\r/mg, '')}');
return { result: t }
} catch (e) {
return { error: e }
}
})()
`).then(res => {
// dispatch to decide what to do in case of 'error' or 'result' in res
/// and consume the result in the output
})
.catch(e => {
// not useful to understand the code error
})
return <button onClick={onClick}>RUN</button>
)
It's working but I am sure there has to be a better way.
How should that be properly handled ?