Want to invoke variables defined in preload from the Electron render process

Asked 2 years ago, Updated 2 years ago, 131 views

I want to invoke the variables defined in the preload from the Electron renderer process.
The Electron version is v19.0.4.

We have created the following code according to the tutorial on the official page:

However, undefined appears.
Where is the cause?

  • main.js
const{app, BrowserWindow, ipcMain}=require("electron");
const path=require("path");

let mainWindow;

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

  mainWindow.loadFile("index.html");
  mainWindow.webContents.openDevTools();
  mainWindow.on("closed",()=>{
    mainWindow = null;
  });
};

  • preload.js
const{contextBridge}=require('electron')

contextBridge.exoseInMainWorld('myAPI',{
  desktop —true
})

  • index.html
...
<script src="./render.js"></script>
...
  • render.js
 console.log (window.myAPI)

javascript electron

2022-09-29 21:48

1 Answers

I solved myself.
It seems that using HTML frames was not working.
(For some reason, javascripts invoked from within the frame cannot be passed)


2022-09-29 21:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.