From 321a91910fedc38a95c9431c1b08961239ccad5f Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Wed, 1 Apr 2020 10:23:45 +0200 Subject: [PATCH] Block page loading while WebSocket is not connected --- assets/js/common/system.js | 14 ++++++++------ assets/js/common/ws.js | 19 +++++++++++++++++++ assets/js/user/userLogin.js | 5 +++-- 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/assets/js/common/system.js b/assets/js/common/system.js index b7a09ec1..e66b9597 100644 --- a/assets/js/common/system.js +++ b/assets/js/common/system.js @@ -11,7 +11,7 @@ ComunicWeb.common.system = { * @param {String} openPage Specify a page to open * @return {Boolean} True for a success */ - init: function(openPage){ + init: async function(openPage){ //Display Comunic logo ComunicWeb.debug.displayComunicLogo(); @@ -66,8 +66,14 @@ ComunicWeb.common.system = { /** * What to do after login refresh */ - var afterLoginRefresh = function(){ + var afterLoginRefresh = async function(){ + // Initialize Websocket if user is connected + if(signed_in()) { + await UserWebSocket.Connect(); + await UserWebSocket.WaitForConnected(); + } + /** * Open a page */ @@ -79,10 +85,6 @@ ComunicWeb.common.system = { //Open specified page ComunicWeb.common.page.openPage(openPage); - // Initialize Websocket if user is connect - if(signed_in()) - UserWebSocket.Connect(); - //End of init ComunicWeb.debug.logMessage("Application is ready !"); } diff --git a/assets/js/common/ws.js b/assets/js/common/ws.js index 9ad0e092..8fd5a056 100644 --- a/assets/js/common/ws.js +++ b/assets/js/common/ws.js @@ -56,6 +56,22 @@ class UserWebSocket { } } + /** + * Wait for the socket to be connected (if not already) + */ + static WaitForConnected() { + return new Promise((res, err) => { + + // Check if we are already connected + if(this.ws.readyState == WebSocket.OPEN) { + res(); + return; + } + + this.ws.addEventListener("open", () => res()); + }); + } + /** * Handles websocket errors */ @@ -69,6 +85,9 @@ class UserWebSocket { */ static async Closed(e) { console.error("WS closed", e) + + // Reset requests queue + requests = {}; // Check if the server was gracefully stopped if(!this.hasOwnProperty("ws")) diff --git a/assets/js/user/userLogin.js b/assets/js/user/userLogin.js index 48eab9ae..6438a394 100644 --- a/assets/js/user/userLogin.js +++ b/assets/js/user/userLogin.js @@ -151,7 +151,7 @@ ComunicWeb.user.userLogin = { }; //What to do after the request is completed - var afterAPIrequest = function(result){ + const afterAPIrequest = async function(result){ //Prepare data return var loginstate = false; @@ -178,7 +178,8 @@ ComunicWeb.user.userLogin = { ComunicWeb.components.mailCaching.set(usermail); // Initialize websocket - UserWebSocket.Connect(); + await UserWebSocket.Connect(); + await UserWebSocket.WaitForConnected(); } //Perform next action if login failed