javascript - 如何在 contextIsolation 设置为 true 时从 HTML 文件访问 require

标签 javascript html node.js electron requirejs

我正在尝试将 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


Full source code

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/

相关文章:

node.js - Loopback异步数据调用Nodejs

javascript - 如何不在 IE 中加载脚本?

javascript - 使用 require.js 加载命名的 TypeScript 模块

javascript - Angular 不使用 ng-click 提交参数

javascript - 指定工具提示位置

node.js - 存储后如何从 MongoDB 中检索二进制文件?

javascript - CoffeeScript 与其他库

javascript - onsubmit 和确认总是处理表单?

javascript - 如何在触发 "option"事件监听器后获取 "change"标记的自定义属性?

node.js - Firebase 自定义登录期间在何处存储 key