MV Save Game on X slot before closing window.

I successfuly managed to write script that allows player to instantly load game from designated slot file directly from title screen, something like "continue last session" or game is picked where player left game, however this script contains a major flaw - of course it's save and load game on user's demand, but it is missing a feature to save game on closing game (closing game means:
- pressing alt+f4
- quitting by default means (esc menu -> exit game)
- closing by pressing [x] in to right corner of window.

So my question is how to handle it? I can only guess it has to do something with window.onclose method, but I'm not quite sure how to handle it with node.js
You could try to register a listener on the "beforeunload" event, like this:
JavaScript:
window.addEventListener('beforeunload', e => {
    ...
});

You won't get user interaction this way, because the window closes when the function returns, but you could probably do an autosave. This should work for Alt + F4 and Clicking the X, for the manual exit you can take a look at Scene_GameEnd, which handles the "to title / cancel" dialogue.
@Iavra - I did see your way on stackoverflow, but in MV for some reason it's not working. I read there are two methods in Global Web API:

window.onbeforeunload and window.onunload and they are used differently, because some browsers support first one and others the second.

I used both but, it doesn't work, even in console.
I did just try it in MZ like this:
JavaScript:
window.addEventListener('beforeunload', e => {
    DataManager.saveGame(0);
});
and it did create an autosave (could replace 0 with a different number to create an actual save, as well) when exiting out using either Alt + F4 or the X. I'm not sure how much saving differs between those 2, though.
@Iavra - did you save it as plugin or placed directly in index.html or main.js?
As this goes a bit more into the maker architecture, i'm going off MZ here, so be aware that things might be different in MV.

I directly executed it in the console prior to closing the game. Just make sure it runs once, so you could extend something like Scene_Boot.prototype.create. You will need to make sure you are actually in the game, though, or you would create a save from the title screen, which could end up doing weird things.
In MZ your code works, but not in MV... Running in parallel event with 10 frames delay saving function could be a disaster, especialy, when game is running on classic HDD... So it's out of question... I'm gonna check one more thing, if it fails... Then I give up... At least for a moment.

Edit: Ok, that setting a eventListener works in MV, but just in case i put in code also events onclose, onunload and onbeforeunload. So, now it's working. Thank you @Iavra

Original thread: https://forums.rpgmakerweb.com/threads/save-game-on-x-slot-before-closing-window.138570/