在关闭 nodeIntegration 的情况下创建自定义窗口控件(如关闭、最小/最大和恢复)时,我被卡住了。我在渲染器的本地 html 文件中创建了按钮
主文件
mainWindow = new BrowserWindow({
x, y, width, height,
frame: false,
show: false,
webPreferences: { devTools: true }
});
mainWindow.loadURL(url.format({
protocol: 'file:',
slashes: true,
pathname: path.join(__dirname, 'assets', 'index.html')
}));
Run Code Online (Sandbox Code Playgroud)
索引.html
<div id='minimize' class='noSelect'></div>
<div id='maximize' class='noSelect'></div>
<div id='restore' class='noSelect'></div>
<div id='close' class='noSelect'></div>
<script type='text/javascript' src='../assets/js/index.js'></script>
Run Code Online (Sandbox Code Playgroud)
默认情况下,nodeIntegration 处于关闭状态,因此index.js
无法访问 Node。但是,我需要能够向按钮添加功能以关闭、最小/最大和恢复窗口。
索引.js
const { remote } = require('electron');
const mainWindow = remote.getCurrentWindow();
document.getElementById('close').addEventListener('click', () => {
mainWindow.close();
});
Run Code Online (Sandbox Code Playgroud)
由于 nodeIntegration 被禁用,这将不起作用。在本地页面中启用它是否安全?如果没有,这样做的安全方法是什么?
我有一个电子应用程序。我的客户端脚本(渲染器)需要访问电子 API,但这给了我一个安全警告,所以我将它移到预加载脚本中并禁用了 nodeIntegration。然后我收到了关于 contextIsolation 的警告,所以我启用了它。我的预加载脚本之前将一个函数附加到客户端可以读取的窗口,如下所示:
window.readClipboard = function(){
return clipboard.readText()
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,上下文隔离意味着客户端无法再访问此功能。有没有办法使这个工作与上下文隔离或我应该禁用它?
额外的细节
让我尝试打开上下文隔离的警告消息如下:
电子弃用警告(contextIsolation 默认更改)此窗口默认禁用上下文隔离。在 Electron 5.0.0 中,上下文隔离将默认启用。要为此更改做准备,请在此窗口的 webPreferences 中设置 {contextIsolation: false},或确保此窗口不依赖于禁用上下文隔离,并设置 {contextIsolation: true}。
在 client.js 我尝试访问:
console.log("window.readClipboard", window.readClipboard)
Run Code Online (Sandbox Code Playgroud)
有输出:
window.readClipboard 未定义
在博客发布后的回购之后,我花了大约一个小时来阅读要点,但似乎无法弄清楚该如何做。
我有一个BrowserWindow
实例,使用加载URL(由我控制)nodeIntegration: false
。
在主要过程中,我想与呈现的URL进行通信。我对preload
脚本BrowserWindow.send
和executeJavascript
范例感到困惑。
我要发送的数据非常大(例如,文件上传介于50kb和10mb之间)。
最好的方法是什么?您可能知道的任何示例/教程都会有所帮助。谢谢!
我正在使用https://github.com/maxogden/menubar使用 Electron 创建菜单栏桌面应用程序。然而,我正在努力建立基本的 IPC 通信。知道为什么下面的代码不起作用吗?为了澄清这一点,我希望test
在应用程序启动时注销到控制台,但事实并非如此。
应用程序.js
const { app } = require('electron');
const Menubar = require('menubar');
const menubar = Menubar.menubar({
index: `file://${__dirname}/index.html`,
preloadWindow: true,
icon: './assets/img/icon.png',
});
try {
require('electron-reloader')(module)
} catch (_) { }
app.on('ready', () => {
menubar.window.webContents.send('test');
});
Run Code Online (Sandbox Code Playgroud)
渲染器.js
const { ipcRenderer } = require('electron');
ipcRenderer.on('test', () => {
console.log('test');
});
Run Code Online (Sandbox Code Playgroud)
索引.html
<html>
<head>
<title>Test</title>
<script>
require('./renderer')
</script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)