我正在尝试将 electron 放入这个 HTML 文件中,但是 require
是未定义的:
<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>
我将 nodeIntegration
设置为 True,将 contextIsolation
设置为 True,用于防止安全警告的 Web 首选项。如何通过这个文件获取require
?
Guide Video Adding Script tags
在 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;
})
}
最佳答案
我遇到的主要问题是,在启用 contextIsolation
的情况下,无法使用 require
。
要在启用contextIsolation
的情况下访问ipcRenderer
,使用预加载文件和contextBridge
来公开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
可以在不启用 contextIsolation
的情况下使用,但这被认为是不安全的。最好只公开某些功能而不是整个对象。
关于javascript - 如何在 contextIsolation 设置为 true 时从 HTML 文件访问 require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64109533/