'Electron contextBridge works on desktop but not on web

My stack consist of Electron, React, FastAPI. I created a contextBridge in the preload.js file. Everything is working fine on the desktop application however when I am on the web, I get the following error below. If anyone knows what might be the cause of this please let me know where to start looking! I don't fully understand why it's a type error. Thank you!

preload.js

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

contextBridge.exposeInMainWorld("api", {
  rollDice: async () => {
    return await ipcRenderer.invoke("roll-dice");
  },
});

error in the browser console

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'rollDice')

You can recreate the bug by following this:

npx create-react-app my-app --template electron-python-fastapi
cd my-app
python -m pip install virtualenv
python -m virtualenv venv
.\venv\Scripts\activate
python -m pip install -r requirements.txt
npm start

Edit: in my App.js file window.api seems to be undefined. Any reason that might be the case for Web but not Desktop?

Edit: I added console.log("running preload"); at the end of my preload.js file and seems like it doesn't preload the file when running on the browser(web).

electron.js

  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      enableRemoteModule: false,
      preload: path.join(__dirname, "preload.js"),
    },
  });


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source