How to properly use preloads and window.api calls in electron?

1k views Asked by At

I am having trouble using a render.js file to write "api" calls from the rendered html page's javascript.

main.js new BrowserWindow function includes:

    webPreferences: {
        nodeIntegration: false, // is default value after Electron v5
        contextIsolation: true, // protect against prototype pollution
        enableRemoteModule: false, // turn off remote
        preload: "preload.js" // use a preload script  
    },

preload.js:

const { ipcRenderer, contextBridge } = require('electron')

contextBridge.exposeInMainWorld(
    "api", {
        send: (channel, data) => {
            let validChannels = ["login"];
            if (validChannels.includes(channel)) {
                ipcRenderer.send(channel, data);
            }
        },
        receive: (channel, func) => {
            let validChannels = ["fromMain"];
            if (validChannels.includes(channel)) {
                ipcRenderer.on(channel, (event, ...args) => func(...args));
            }
        }
    }
);

passwordPage.js linked in passwordPage.html:

document.getElementById("login").addEventListener('click', function() {
    window.api.send("login", "test");
})

error in console of passwordPage:

Uncaught TypeError: Cannot read property 'send' of undefined
1

There are 1 answers

0
elkeis On

According to docs:

The value should be the absolute file path to the script.

Try to use `${__dirname}/preload.js` or something equal.