From 36b9572bb13df8dfc1d940dce0b891c67ea03243 Mon Sep 17 00:00:00 2001 From: Mark VanLandingham Date: Fri, 23 Jun 2023 11:32:34 -0500 Subject: [PATCH] FIX: Attempt to reconnect to server when browser visibilty changes (#22259) --- .../app/services/network-connectivity.js | 34 ++++++++++--------- app/assets/javascripts/service-worker.js.erb | 2 +- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/app/assets/javascripts/discourse/app/services/network-connectivity.js b/app/assets/javascripts/discourse/app/services/network-connectivity.js index 6031b5e9585..ac4a846742e 100644 --- a/app/assets/javascripts/discourse/app/services/network-connectivity.js +++ b/app/assets/javascripts/discourse/app/services/network-connectivity.js @@ -13,29 +13,31 @@ export default class NetworkConnectivity extends Service { this.setConnectivity(navigator.onLine); window.addEventListener("offline", () => { - this.handleConnectivityChangeEvent(false); + this.setConnectivity(false); }); - window.addEventListener("online", () => { - this.handleConnectivityChangeEvent(true); - }); + window.addEventListener( + "online", + this.pingServerAndSetConnectivity.bind(this) + ); + + window.addEventListener("visibilitychange", this.onFocus.bind(this)); } - handleConnectivityChangeEvent(connected) { - if (connected) { - // Make a super cheap request to the server. If we get a response, we are connected! - return ajax("/srv/status", { dataType: "text" }) - .then((response) => { - this.setConnectivity(response === "ok"); - }) - .catch(() => { - this.setConnectivity(false); - }); - } else { - this.setConnectivity(false); + onFocus() { + if (!this.connected && document.visibilityState === "visible") { + this.pingServerAndSetConnectivity(); } } + async pingServerAndSetConnectivity() { + let response = await ajax("/srv/status", { dataType: "text" }).catch(() => { + this.setConnectivity(false); + }); + + this.setConnectivity(response === "ok"); + } + setConnectivity(connected) { this.connected = connected; diff --git a/app/assets/javascripts/service-worker.js.erb b/app/assets/javascripts/service-worker.js.erb index 3a320b0d83b..08a5a120337 100644 --- a/app/assets/javascripts/service-worker.js.erb +++ b/app/assets/javascripts/service-worker.js.erb @@ -19,7 +19,7 @@ workbox.setConfig({ debug: false }); -var authUrls = ["auth", "session/sso_login", "session/sso"].map(path => `<%= Discourse.base_path %>/${path}`); +var authUrls = ["auth", "session/sso_login", "session/sso", "srv/status"].map(path => `<%= Discourse.base_path %>/${path}`); var chatRegex = /\/chat\/channel\/(\d+)\//; var inlineReplyIcon = "<%= UrlHelper.absolute("/images/push-notifications/inline_reply.png") %>";