0

I am trying to create a game where when the player closes his window the mongo database is changed to “player1 is inactive”.

This is the code I have in main.js:

window.addEventListener('beforeunload', function (e) {
   Games.update({_id : myGuy},{$set:{active : 0}});
  // Cancel the event
e.preventDefault();
  // Chrome requires returnValue to be set
  e.returnValue = '';
});

It works sporadically in Firefox and pretty much never in Chrome. ?I’m thinking maybe meteor might change the local mini mongo but doesn’t know to change the mongo on the server? (Just a thought.)

dennis
  • 153
  • 2
  • 9
  • Interestingly, in Chrome, if I respond to the browser prompt: "Do you want to leave this site?" with "stay". And then try to close the window a second time and say "leave", mongo resets correctly. I don't know what that means. – dennis May 16 '19 at 23:20
  • Is this related to the client side code? – Jankapunkt May 17 '19 at 08:14
  • it's a chrome bug https://bugs.chromium.org/p/chromium/issues/detail?id=866818 More explained in https://stackoverflow.com/questions/9626059/window-onbeforeunload-in-chrome-what-is-the-most-recent-fix Prompt an alert box should prevent your issue – Jimish Gamit May 17 '19 at 19:11

1 Answers1

0

In response to  Jankapunkt, the above code is on the client side, but I still have “autopublish” turned on, so that shouldn’t be a problem.

In response to Jimish Gamit, thanks for the info. It does indeed seem to be a Chrome bug. I tried the alert box, which didn’t seem to help.

window.addEventListener('beforeunload', function (e) {
Games.update({_id : myGuy},{$set:{active : 0}});
 e.preventDefault();
 return "alert" 
})

As a work around, I just created a custom aframe component that creates a key that can reset the players to inactive when needed, which is the best I can do I guess.

AFRAME.registerComponent('reset', {
    init: function() {
      document.addEventListener('keydown', (event) => {
      const keyName = event.key;
      if (keyName === 'r') {
                if (Games.findOne()) {
                  var playerId1 = Games.findOne({name: "player1"})._id;
                  var playerId2 = Games.findOne({name: "player2"})._id; 
                  Games.update({_id : playerId1},{$set:{active : 0}});
                  Games.update({_id : playerId2},{$set:{active : 0}});
                }
           }
        })
     }
  }) 
dennis
  • 153
  • 2
  • 9