How to access require, from an HTML file, when contextIsolation is set to true

Viewed 583

I’m trying to get electron into this HTML file, but require is undefined:

<script>
    const electron = require("electron");
    const {icpRenderer} = electron;

    const form = document.querySelector("form");
    form.addEventListener("submit", submitForm);

    function submitForm(e){
        e.preventDefault();
        const item = document.querySelector("#item").value;
    }
</script>

I have nodeIntegration as True, and contextIsolation as True for the web preferences which is used to prevent security warnings. How can I get require through this file?


Full source code

Guide Video Adding Script tags

In main.js:

function createAddWindow(){
    addWindow = new BrowserWindow({
        width: 300,
        height: 200,
        title: "Add Inventory Item",
        webPreferences: {
            nodeIntegration: true,
            worldSafeExecuteJavaScript: true,
            contextIsolation: true
        }
    });

    addWindow.loadURL(url.format({
        pathname: path.join(__dirname, "addWindow.html"),
        protocol: "file",
        slashes: true
    }));

    addWindow.on("close", function(){
        addWindow = null;
    })
}
1 Answers

The main problem I was having was that with contextIsolation enabled it's not possible to use require.

To access ipcRenderer with contextIsolation enabled, a preload file is used with contextBridge to expose certain functions from ipcRenderer:

preload.js

const { contextBridge, ipcRenderer } = require("electron");

contextBridge.exposeInMainWorld("myAPI", {
    ipcSend: (...args) => ipcRenderer.send(...args),

    ipcOn: (key, handler) => ipcRenderer.on(key, (event, ...args) => handler(...args))
});

main.js

function createAddWindow(){
    subWindowOpen = true;
    addWindow = new BrowserWindow({
        width: 400,
        height: 300,
        title: "Add Inventory Item",
        webPreferences: {
            worldSafeExecuteJavaScript: true,
            contextIsolation: true,
            preload: path.join(__dirname, "preload.js")
        }
    });

    addWindow.loadURL(url.format({
        pathname: path.join(__dirname, "addWindow.html"),
        protocol: "file",
        slashes: true
    }));
}

addWindow.html

<script>
    myAPI.ipcSend("item:add", item);
</script>

nodeIntegration could be used instead without contextIsolation enabled, but this is considered to be unsafe. It's better to expose only certain functions rather than the whole object.

Related