Ниже приведен мой код:
Main.js
Код: Выделить всё
const { app, BrowserWindow } = require('electron');
const path = require('path');
let mainWindow;
const createWindow = () => {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true, // Ensuring context isolation is enabled
preload: path.join(__dirname, 'preload.js'), // Path to preload script
},
});
const localFilePath = path.join(__dirname, 'dist', 'frontend-installers', 'index.html');
const localFileURL = `file://${path.normalize(localFilePath)}`;
mainWindow.loadURL(localFileURL);
console.log('Main window loaded');
mainWindow.webContents.openDevTools();
};
app.whenReady().then(createWindow);
Код: Выделить всё
console.log('preload running');
const { contextBridge, ipcRenderer } = require('electron');
console.log('Context Isolated:', process.contextIsolated);
if (process.contextIsolated) {
try {
contextBridge.exposeInMainWorld('electron', {
ipcRenderer: ipcRenderer
});
console.log("ipcRenderer exposed successfully!");
} catch (error) {
console.error("Error exposing ipcRenderer:", error);
}
}
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector);
if (element) element.innerText = text;
};
for (const dependency of ['chrome', 'node', 'electron']) {
replaceText(`${dependency}-version`, process.versions[dependency]);
}
try {
console.log('window:', window);
console.log('window.electron:', window.electron); // window.electron is undefined here
} catch (error) {
console.error('Error accessing window.electron:', error);
}
});
Скрипт preload.js выполняется успешно (я вижу журнал выполнения предварительной загрузки в консоли).
process.
contextIsolated имеет значение true, что означает, что изоляция контекста включена правильно.
ipcRenderer успешно подвергается воздействию window.electron (согласно журналу внутри preload.js).
Почему window.electron даже не определен после того, как ipcRenderer предоставляется с помощью contextBridge?
И как я могу гарантировать, что window.electron будет доступен в процессе рендеринга после его предоставления?
Подробнее здесь: https://stackoverflow.com/questions/793 ... idge-in-el
Мобильная версия