Javascript 我是否能够安全地访问特定的electron API?

Javascript 我是否能够安全地访问特定的electron API?,javascript,node.js,electron,Javascript,Node.js,Electron,因此,我需要找到一种方法来创建自定义窗口标题栏按钮,这样我就可以安全地添加功能,而无需在electron中启用节点集成。我想这可能是我所需要的,但我不确定这是如何工作的,或者它是否适用于这个 由于我正在使用HTML、CSS和Javascript创建自定义窗口按钮,因此我需要以下方法: mainWindow.minimize(); mainWindow.close(); mainWindow.getBounds(); mainWindow.setBounds(...); mainWindow.se

因此,我需要找到一种方法来创建自定义窗口标题栏按钮,这样我就可以安全地添加功能,而无需在electron中启用节点集成。我想这可能是我所需要的,但我不确定这是如何工作的,或者它是否适用于这个

由于我正在使用HTML、CSS和Javascript创建自定义窗口按钮,因此我需要以下方法:

mainWindow.minimize();
mainWindow.close();
mainWindow.getBounds();
mainWindow.setBounds(...);
mainWindow.setResizable(...);
这是在渲染器过程中,因此需要启用节点集成,并且需要像这样使用远程:

const { remote } = require('electron');
const mainWindow = remote.getCurrentWindow();

我是否可以在禁用节点集成的情况下使用预加载选项来访问这些方法,以便向自定义按钮添加功能?如果是,怎么做?这样安全吗?

您可以添加一个提供一些API的预加载脚本,如下所示:

const { remote } = require("electron");

function initialise () {
    window.Controls = {
        minimize: () => { remote.getCurrentWindow ().minimize (); },
        close: () => { remote.getCurrentWindow ().close (); },
        getBounds: () => { remote.getCurrentWindow ().getBounds (); },
        setBounds: (bounds) => { remote.getCurrentWindow ().setBounds (bounds); },
        setResizable: (resizable) => { remote.getCurrentWindow ().setResizable (resizeable); }
    };
}

initialise ();
然后,可以在渲染器过程中使用如下定义的函数:

document.getElementById ("close-button").addEventListener ("click", (e) => {
    window.Controls.close ();
});

这通过在Browser窗口上仅设置nodeIntegration:true来降低执行不安全代码的风险。但是,所有可以访问window.Controls的代码都将能够操纵窗口状态。

是否需要启用contextIsolation或sandbox才能工作?仅在BrowserWindow的webPreferences中启用沙盒并传递脚本路径以预加载。然而,contextIsolation不是最糟糕的事情,但在这种情况下不是必需的?文档是预加载脚本,在不启用沙箱的情况下也可以工作。但是,启用沙箱更安全,因为包括预加载脚本在内的每个进程都有自己的API集。即使您在预加载中不使用第三方模块,也可以仅为了前向兼容性而启用sandbox。将来您可能会添加第三方模块进行预加载,而忘记启用sandbox。。。。