首页 > 解决方案 > 通过函数调整电子窗口大小

问题描述

几天来我一直试图找到答案,但似乎找不到一个好的解决方案。

我对 Eelectron 还很陌生,但我正在尝试创建一个应用程序,在该应用程序中我可以在事件之后调用一个函数,然后调整窗口大小。

到目前为止我所看到的,我必须使用 icpMain 和 icpRender,但是每当我尝试执行建议的代码时,我要么在我的脚本中加载问题,要么得到一个“未定义”的错误。

主.js:

const electron  = require('electron');
const {ipcMain} = require('electron');
const url       = require('url');
const path      = require('path');
const {app, BrowserWindow} = electron;
let mainWindow;
app.on('ready',function(){
    mainWindow = new BrowserWindow({
        transparent:    true,
        frame:          false,
        width:          500,
        height:         500,
        webPreferences: {
            preload: path.join(__dirname,'js/login.js')
        }
    });
    //mainWindow.removeMenu();
    mainWindow.loadURL(url.format({
        pathname:   path.join(__dirname,'html/login.html'),
        protocol:   'file:',
        slashes:    true
    }))
    ipcMain.on('resize-me-please', (event, arg) => {
        mainWindow.setSize(300,300)
    })
});

标签: jquerynode.jselectron

解决方案


我终于弄明白了。

在你的 main.js 中确保你在 app 对象中设置了以下内容:

webPreferences: {
    nodeIntegration: true,
    contextIsolation: false,
    enableRemoteModule: true,
}

完整示例:

const electron  = require('electron');
const url       = require('url');
const path      = require('path');
const {app, BrowserWindow} = electron;
let mainWindow;
app.on('ready',function(){
    mainWindow = new BrowserWindow({
        transparent:    true,
        frame:          false,
        width:          500,
        height:         500,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true,
        }
    });
    //mainWindow.removeMenu();
    mainWindow.loadURL(url.format({
        pathname:   path.join(__dirname,'html/login.html'),
        protocol:   'file:',
        slashes:    true
    }))
});

然后,如果您使用 jquery 和 jquery-UI 之类的库,请确保使用以下命令安装它:

  • npm install jquery --save
  • npm install jquery-ui --save

然后在您的 index.html 中您需要使用 jquery,这也可以通过文件来完成,您可以通过以下命令执行此操作:

<script>window.$ = window.jQuery = require('jquery');</script>

现在您可以通过在您的 js 文件中使用它来使用您的 js 执行远程功能:

const {BrowserWindow} = require('electron').remote;
var theWindow = BrowserWindow.getFocusedWindow();

现在您可以使用以下命令设置、获取最大化、最小化和关闭应用程序:

theWindow.close();

推荐阅读