Skip to content
Advertisement

Electron window reloads when saved file is overwriten / replaced

So, I have the save function written and it works exactly as intended the first time I save a file. However, if I try to overwrite the file by saving it again, the file saves fine, but the window reloads clearing all the data that’s been entered. I can just load the saved file and continue editing, but that will get annoying fast. I cannot find any info on how to resolve this issue, anywhere. Any help would be greatly appreciated.

function saveData(){
  let data = {}
  data.item1 = getItem1()
  data.item2 = getItem2()
  data.item3 = getItem3()
  // convert data object to a string
  let dataString = JSON.stringify(data, null, 4)
  // open save dialog and chooses path
  let savePath = dialog.showSaveDialog({filters: [{name: 'Save File', extensions: ['json']},]})
  // save file to disk
  if (savePath != undefined){
    fs.writeFile(savePath, dataString, function(err) {
    // file saved or err
    })
  }
}

And here is the menu template entry:

{ label: 'File',
  submenu: [
    { label: 'New', click: SendEvent('file-new')},
    { label: 'Open', click: SendEvent('file-open')},
    { label: 'Save', accelerator: 'CmdOrCtrl+S', click: function(){
            saveData();
      }
    },

    { label: 'Save As',
        accelerator: 'CmdOrCtrl+Shift+S',
        click: SendEvent('file-save-as')},
    { label: 'Close', click: SendEvent('file-close')},
    { type: 'separator'},
    { label: 'Quit', accelerator: 'CmdOrCtrl+Q', click: function() {app.quit();}},
    { type: 'separator' },
    { label: 'Print', accelerator: 'CmdOrCtrl+P', click(){win.webContents.print({silent: false, printBackground: false})} }
    ]
},

And the getItem1 function:

function getItem1(){
    const item1 = document.getElementById('itemID').src
    return item1
}

Advertisement

Answer

Now I’m feeling a bit dumb. It turns out that the reason it was reloading was because I’m using the electron-reload package to automatically reload the page when I save the source files. It was also causing the page to reload when the save file was overwritten. Good to know going forward.

Edit:

You can tell electron-reload to ignore a directory by ammending your require statement to look something like this:

require('electron-reload')(__dirname, {ignored: /<folder_to_be_ignored>|[/\]./});

https://github.com/yan-foto/electron-reload#api

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement