Skip to content Skip to sidebar Skip to footer

Are There Any Window Events Triggered If User "pulls The Plug" And Shuts Down Their Computer?

I have a website, and I only want the client to be able to have 1 WebSocket connection at a time (when they open another tab while there is already another connection display, I di

Solution 1:

As correctly stated in Jaromanda's comment, a computer without power can not emit an Event to the browser (which doesn't even exist anymore...).

However, one solution to your root problem is to listen to the storage event.

This event will fire across all the Windows that do share the same Storage area, when an other Window will make any modification to this Storage.

So we can use it as a mean to communicate between Windows from the same domain, in almost real time. This means that you don't have to keep your flag up to date, you can now know directly if an other Window is already active.

Here is a basic implementation. I'll let you the joy of making it more suited to your needs.

let alone = true; // a flag to know if we are alone
onstorage = e => { // listen to the storage eventif(e.key === 'am_I_alone') {
    if(e.newValue === 'just checking') { // someone else is asking for permissionlocalStorage.am_I_alone = 'false'; // refuse
    }
    elseif(e.newValue === 'false') { // we've been refused access
      alone = false;
    }
  }
};

localStorage.am_I_alone = 'just checking'; // trigger the event on the other WindowssetTimeout(()=>{ // let them a little time to answerif(alone) { // no response, we're good to go// so the next one can trigger the eventlocalStorage.am_I_alone = "true";
    startWebSocket();
  }
  else { // we've been rejected...error();
  }
}, 500);

Live Plnkr

Post a Comment for "Are There Any Window Events Triggered If User "pulls The Plug" And Shuts Down Their Computer?"