Электрон - закрыть начальное окно, но оставить ребенка открытым

1

Я кодирую электронное приложение, которое должно загружать заставку, а затем открывать новое окно. Впоследствии экран заставки должен быть закрыт.

Однако я не могу этого сделать. В моем index.js, сценарии запуска, у меня есть следующий код:

const { app, BrowserWindow } = require("electron");

app.on("ready", () => {
    let win = new BrowserWindow({ /*...*/ });
    win.loadURL('file://${__dirname}/splash/splash.html');
    win.on("ready-to-show", () => { win.show(); });
    win.on("closed",        () => { app.quit(); });
});

В splash.html загружаю splash.js, используя

<script>require("./splash");</script>

И в splash.js я попробовал следующий код:

const remote = require("electron").remote;

let tWin = remote.getCurrentWindow();

let next = function(){ 
    let win = new remote.BrowserWindow({ /*...*/ });
    win.loadURL('file://${__dirname}/main/main.html');
    win.on("ready-to-show", () => { win.show(); });
    win.on("closed",        () => { app.quit(); });

    tWin.close();

    // I could just use win.hide(); here instead 
    // of tWin.close(); but that can't really be the right way.
};

Функция next() вызывается после таймаута. Проблема заключается в том, что если вызывается, главное окно отображается на секунду, но оба: slpash и main закрываются мгновенно.

Я попытался исправить это, комментируя

win.on("closed", () => { app.quit(); });

в моем index.js. Но это привело к следующей ошибке:

Попытка вызвать функцию в окне рендеринга, которое было закрыто или выпущено.

Uncaught Exception:
Error: Attempting to call a function in a renderer window that has been closed or released. Function provided here: splash.js:38:9.
    at BrowserWindow.callIntoRenderer (/usr/lib/node_modules/electron-prebuilt/dist/resources/electron.asar/browser/rpc-server.js:199:19)
    at emitOne (events.js:96:13)
    at BrowserWindow.emit (events.js:188:7)

Кто-нибудь есть идея о том, как предотвратить закрытие вновь созданного окна?

  • 0
    почему вы хотите загрузить заставку в другое окно. Тебе не нравится этот код?
  • 0
    Вы должны загрузить «всплеск» и «главное» окно в одном и том же процессе, а затем показать / скрыть в зависимости от нужных вам событий, я опубликую ответ с моим примером кода.
Теги:
electron

1 ответ

1
Лучший ответ

Обычно я использую другой подход. Вот как это делается:

  1. создайте глобальную ссылку на переменную для главного окна и окна всплеска, если это не будет закрыто сборщиком мусора.
  2. загрузить ' splash ' browserwindow
  3. в событии 'show' Я вызываю функцию для загрузки " главного " окна
  4. в главном окне "dom-ready", я закрываю " всплеск " и показываю " главное ",

Вот один пример моего электронного кода main.js, не стесняйтесь спрашивать:

   'use strict';

    //generic modules
    const { app, BrowserWindow, Menu } = require('electron');
    const path = require('path')
    const url = require('url')

    const config = require('./config'); //                              => 1: archivo de configuracion
    const fileToLoad = config.files.current ? config.files.current : config.files.raw;
    const jsonData = require(fileToLoad); //                            => 2: archivo de datos (json) 
    const pug = require('electron-pug')({ pretty: true }, jsonData); // => 3: pasamos datos ya tratados a plantillas pug/jade 


    // 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, loading
    app.mainWindow = win;

    function initApp() {
        showLoading(initPresentation)
    }

    function showLoading(callback) {
        loading = new BrowserWindow({ show: false, frame: false })
        loading.once('show', callback);
        loading.loadURL(url.format({
            pathname: path.join(__dirname, '/src/pages/loading.html'),
            protocol: 'file:',
            slashes: true
        }))

        loading.show();
    }

    function initPresentation() {
        win = new BrowserWindow({
            width: 1280,
            height: 920,
            show: false,
            webPreferences: {
                experimentalFeatures: true
            }
        })
        win.webContents.once('dom-ready', () => {
                console.log("main loaded!!")
                win.setMenu(null);
                win.show();
                loading.hide();
                loading.close();
            })
            // 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.loadURL(url.format({
            //pathname: path.join(__dirname, '/src/pages/home.pug'),
            pathname: path.join(__dirname, '/lab/pug/index.pug'),
            protocol: 'file:',
            slashes: true
        }))

        win.webContents.openDevTools() // Open the DevTools.
    }

    // This method will be called when Electron has finished
    // initialization and is ready to create browser windows.
    // Some APIs can only be used after this event occurs.
    app.on('ready', initApp)

    // Quit when all windows are closed.
    app.on('window-all-closed', () => {
        // On macOS it is common for applications and their menu bar
        // to stay active until the user quits explicitly with Cmd + Q
        if (process.platform !== 'darwin') {
            app.quit()
        }
    })

    app.on('activate', () => {
        // On macOS it common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (win === null) {
            initApp()
        }
    })

    // In this file you can include the rest of your app specific main process
    // code. You can also put them in separate files and require them here.*/
  • 1
    Это потрясающе. Большое спасибо! Отлично работает :)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню