电子防止主窗口关闭

时间:2017-08-14 15:07:41

标签: javascript electron

我正在用电子编写一个应用程序,如果用户打开了未保存的文件,我想在保存之前提示用户。我在网上找到了这个示例代码:

window.onbeforeunload = (e) => {
      var answer = confirm('Do you really want to close the application?');
      e.returnValue = answer;  // this will *prevent* the closing no matter what value is passed
      if(answer) { mainWindow.destroy(); }  // this will close the app
    };

如果在出现的几秒钟内按下对话框是,取消或X按钮,但是如果您让对话框在屏幕上停留一点然后单击一个按钮,无论按下什么内容,应用程序都会关闭

此代码位于index.html

调用的主脚本文件中

3 个答案:

答案 0 :(得分:2)

真奇怪的行为!我无法解释它为什么会发生,但可以为您提供在主流程中实施的解决方法。

您可以使用电子dialog模块并使用电子创建相同的确认对话框。这个按预期工作。

main.js

const { app, BrowserWindow, dialog } = require('electron')
const path = require('path')

app.once('ready', () => {
  let win = new BrowserWindow()
  win.loadURL(path.resolve(__dirname, 'index.html'))
  win.on('close', e => {
    let choice = dialog.showMessageBox(
      win,
      {
        type: 'question',
        buttons: ['Yes', 'No'],
        title: 'Confirm',
        message: 'Do you really want to close the application?'
      }
    )
    if (choice === 1) e.preventDefault()
  })
})

答案 1 :(得分:0)

只有在激活DevTools窗口时才可能。

在任何情况下,更喜欢使用上面提到的pergy关闭事件。这是迄今为止最好的方法。

但要注意e.preventDefault()正在代码中的任何地方传播。正确管理preventDefault()后,您需要将变量e.defaultPrevented = false设置为恢复应用的自然行为。

实际上,在您更改其值之前,似乎e.preventDefault()函数将变量e.defaultPrevented变为true

答案 2 :(得分:0)

在我的情况下,我不得不使用一个名为modificationEnCours的变量,当我不想关闭窗口时,该变量为true;如果想要这样,则使用false

let mainWindow 
let mainMenu // Menu de la fenêtre principale

app.on('ready', () => {
  // Listen for app to be ready

  // Create the mainWindow 
  mainWindow = new BrowserWindow({
    width: 1024,
    height: 768,
    minHeight: 350,
    minWidth: 500,
    frame: true, 
    webPreferences: {
      nodeIntegration: true
    }
    })

  // Quit app when window is closed
  mainWindow.on('close', function(e){
    console.log('close')
    if (modificationEnCours){
      e.preventDefault()
    
      if(msgBoxVerifieSauvegarde('Question','Voulez-vous enregistrer avant de quitter ?')) {
        modificationEnCours=false
        app.quit()
      }
    } else if (process.platform !== 'darwin') {
      modificationEnCours=false
      app.quit()
      mainWindow = null
    }
  })


  // Load html in window
  mainWindow.loadFile(path.join(__dirname, 'mainWindow.html'))


  // Build menu from template
  mainMenu = Menu.buildFromTemplate(mainMenuTemplate)
  // Insert menu
  Menu.setApplicationMenu(mainMenu)
})