gpt4 book ai didi

javascript - 即使在新窗口上调用 show() 函数后,Electron js 桌面应用程序也不显示

转载 作者:行者123 更新时间:2023-12-03 12:25:16 26 4
gpt4 key购买 nike

我是 Electron js 的新手,但是当我运行 npm run start 时在命令行上,窗口似乎有时会显示,但有时也不显示。我不知道出了什么问题。我什至尝试删除 show : false新创建的 BrowserWindow 的一部分但是,运行 npm run start 后仍然出现同样的问题再过几次。当我使用 Electron-packager 打包应用程序时,我仍然面临同样的问题
编辑:我发现当我删除renderer.js文件中的所有代码时,它工作得很好,但是当我把代码放回去时,它会产生这个问题,所以问题可能出在渲染器进程上
在 .app/main.js

  // const {menu_template, save_as_id} = require('./app-menu');
const {app, BrowserWindow, Menu, dialog, ipcMain} = require('electron');
const path = require('path');

/**
* Create a new window when called
*/
function createWindow() {
let x; // Window x cordinate or horizontal position on screen
let y; // Window y cordinate or vertical position on screen

if (BrowserWindow.getAllWindows().length >= 3) return;

const focusedWindow = BrowserWindow.getFocusedWindow();
if (focusedWindow) {
let [posX, posY] = focusedWindow.getPosition();
// Log the window position
console.log(` Window position
x : ${posX}, y : ${posY}`);

if (!focusedWindow.isNormal())
posX = posY = 50;
// Randomly place the window on the screen
const randX = Math.round(Math.random() * 20);
const randY = Math.round(Math.random() * 20);
const _randX = -randX - 5;
const _randY = -randY - 5;

x = posX + (randX <= 10 ? _randX : randX);
y = posY + (randY <= 10 ? _randY : randY);
// check if window is not fully visible
const isOffScreen = x < 0 || y < 0;
// then set the window in a specific position: 60
if (isOffScreen)
x = y = 60;
}

// Create a new browser window
let newWindow = new BrowserWindow({
x,
y,
minWidth: 300,
minHeight: 300,
show: false,
webPreferences: {
enableRemoteModule: true,
nodeIntegration: true,
preload: path.join(__dirname, 'preload.js')
}

});

newWindow.on('closed', () => {
newWindow = null;
});

newWindow.loadFile('./app/index.html');
newWindow.once('ready-to-show', () => {
// now show the current window, when GUI has been loaded to the window
newWindow.show();
console.log('Window ready to show');

// set the window title to indicate that the current file is unnamed
// and needs to be saved
newWindow.setTitle('Untitled - NoteEditor');
});
}

// Create new window on application first startup
app.whenReady().then(() => {
// Menu.setApplicationMenu(menu_template);
createWindow();
})

/**
* Simply sets the `targetWindow`'s title, to `title`
* @param {*} targetWindow to recipient for title change
* @param {*} title the new title of window
*/
const setWindowTitle = (targetWindow, title) => targetWindow.setTitle(title);

exports.createWindow = createWindow;
// exports.chooseFile = chooseFile;
exports.setWindowTitle = setWindowTitle
在 ./app/renderer.js
 const {ipcRenderer, remote} = require("electron");
const mainProcess = remote.require('./main.js');
const app = remote.app;

var text = document.getElementById('text'); // The TextArea
var initialTextContent;
var g_targetTitle;


// when a key is pressed, display status showing that text has been edited and needs to be saved
text.addEventListener('keyup', () => {
const target = remote.getCurrentWindow();
let changedIndicatorChar = '*';
let _windowTitle = target.getTitle();
let isWindowStartUp = _windowTitle.startsWith('Untitled');

// revert the window title to initial title if changes were removed
if (text.value == initialTextContent)
mainProcess.setWindowTitle(target, g_targetTitle);

// should not set window title again based on this constraints
if (!isWindowStartUp && !_windowTitle.startsWith('*') && !_windowTitle.endsWith('txt')) {
let newWindowTitle = changedIndicatorChar + _windowTitle;
mainProcess.setWindowTitle(target, newWindowTitle);
}
});
在 ./app/index.html
 <!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Note Editor</title>
<link rel="stylesheet" href="style.css">
</head>

<body>
<textarea id="text"></textarea>
</body>
<script src="./renderer.js"></script>

</html>

最佳答案

我建议你阅读我的 introduction to electron首先发布,因为它是很好的知识。
这里有几件事在咬你:

  • 您正在创建的新窗口正在收集垃圾,因为 let newWindowfunction createWindow() .您需要在此函数之外存储对这些窗口的引用。 An example .
  • 我不推荐使用 remotenodeIntegration .这些是容易出现安全问题的旧方法。 This post也有一些很好的信息。

  • 这是您尝试做的事情,以此为起点。它不能完全处理多个窗口,但我认为您可以扩展它以帮助您入门!
    main.js
    const {
    app,
    BrowserWindow,
    ipcMain
    } = require("electron");
    const path = require("path");

    // Keep a global reference of the window object, if you don't, the window will
    // be closed automatically when the JavaScript object is garbage collected.
    let win;

    async function createWindow() {

    // Create the browser window.
    win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
    nodeIntegration: false, // is default value after Electron v5
    contextIsolation: true, // protect against prototype pollution
    enableRemoteModule: false, // turn off remote
    preload: path.join(__dirname, "preload.js") // use a preload script
    }
    });

    // Load app
    win.loadFile("./app/index.html");

    // Emitted when the window is closed.
    win.on("closed", () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null;
    });

    win.once("ready-to-show", () => {
    // now show the current window, when GUI has been loaded to the window
    win.show();
    console.log("Window ready to show");

    // set the window title to indicate that the current file is unnamed
    // and needs to be saved
    win.setTitle("Untitled - NoteEditor");
    });
    }

    app.on("ready", createWindow);

    ipcMain.on("toMain", (event, args) => {
    win.setTitle(args);
    });
    preload.js
    const {
    contextBridge,
    ipcRenderer
    } = require("electron");

    // Expose protected methods that allow the renderer process to use
    // the ipcRenderer without exposing the entire object
    contextBridge.exposeInMainWorld(
    "api", {
    changeTitle: (title) => {
    ipcRenderer.send("toMain", title);
    }
    }
    );
    index.html
    <!doctype html>
    <html lang="en-US">
    <head>
    <meta charset="utf-8"/>
    <title>Title</title>
    </head>
    <body>
    <script>
    // Update the title of the window
    window.api.changeTitle("new title");
    </script>
    </body>
    </html>

    关于javascript - 即使在新窗口上调用 show() 函数后,Electron js 桌面应用程序也不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63866077/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com