Modifying the management of the webSocket when Out of Focus of Tab

This commit is contained in:
Silversthorn 2023-08-10 18:40:32 +02:00
parent eccac2508d
commit 372fd04948
2 changed files with 137 additions and 67 deletions

View File

@ -232,6 +232,7 @@
let usingWebSockets = false; let usingWebSockets = false;
let webSocket = null; let webSocket = null;
let websocketTimeoutId = null;
// {% if request.protocol == 'https' %} // {% if request.protocol == 'https' %}
usingWebSockets = true; usingWebSockets = true;
@ -282,6 +283,7 @@
wsOpen = false; wsOpen = false;
console.log('Closed WebSocket', closeEvent); console.log('Closed WebSocket', closeEvent);
if (!document.hidden) {
if (typeof reconnectorId !== 'number') { if (typeof reconnectorId !== 'number') {
setTimeout(sendWssError, 7000); setTimeout(sendWssError, 7000);
} }
@ -291,9 +293,9 @@
reconnectorId = setTimeout(startWebSocket, (getRandomArbitrary(0, 2 ** failedConnectionCounter - 1) + 5) * 1000) reconnectorId = setTimeout(startWebSocket, (getRandomArbitrary(0, 2 ** failedConnectionCounter - 1) + 5) * 1000)
failedConnectionCounter++; failedConnectionCounter++;
}
}; };
webSocket = { webSocket = {
on: function (event, callback) { on: function (event, callback) {
console.log('registered ' + event + ' event'); console.log('registered ' + event + ' event');
@ -319,6 +321,21 @@
warn('WebSockets are not supported in Crafty if not using the https protocol') warn('WebSockets are not supported in Crafty if not using the https protocol')
// {% end%} // {% end%}
// Managing Connexions for Multi Tab opened to reduce bandwith usage
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
websocketTimeoutId = setTimeout(() => {
webSocket.close(1000, "Closed due to Inactivity");
console.log('%c[Crafty Controller] %cClose Websocket due to Tab not active after 5s', 'font-weight: 900; color: #800080;', 'font-weight: 900; color: #eee;');
}, 5000);
} else {
clearTimeout(websocketTimeoutId)
if (webSocket.getStatus() == WebSocket.CLOSED) {
startWebSocket();
}
}
});
if (webSocket) { if (webSocket) {
webSocket.on('send_start_error', function (start_error) { webSocket.on('send_start_error', function (start_error) {
var x = document.querySelector('.bootbox'); var x = document.querySelector('.bootbox');
@ -509,10 +526,10 @@
document.addEventListener('alpine:init', () => { document.addEventListener('alpine:init', () => {
console.log('%c[Crafty Controller] %cAlpine.js pre-initialization!', 'font-weight: 900; color: #800080;', 'color: #eee;'); console.log('%c[Crafty Controller] %cAlpine.js pre-initialization!', 'font-weight: 900; color: #800080;', 'color: #eee;');
}) });
document.addEventListener('alpine:initialized', () => { document.addEventListener('alpine:initialized', () => {
console.log('%c[Crafty Controller] %cAlpine.js initialized!', 'font-weight: 900; color: #800080;', 'color: #eee;'); console.log('%c[Crafty Controller] %cAlpine.js initialized!', 'font-weight: 900; color: #800080;', 'color: #eee;');
}) });
$(document).ready(function () { $(document).ready(function () {
console.log('%c[Crafty Controller] %cReady for JS!', 'font-weight: 900; color: #800080;', 'font-weight: 900; color: #eee;'); console.log('%c[Crafty Controller] %cReady for JS!', 'font-weight: 900; color: #800080;', 'font-weight: 900; color: #eee;');

View File

@ -55,19 +55,46 @@
<script src="/static/assets/js/shared/hoverable-collapse.js"></script> <script src="/static/assets/js/shared/hoverable-collapse.js"></script>
<script src="/static/assets/js/shared/misc.js"></script> <script src="/static/assets/js/shared/misc.js"></script>
<!-- endinject --> <!-- endinject -->
{% block js %}
<!-- Custom js for this page -->
<script> <script>
/* Script for WebSockets */
let usingWebSockets = false;
let webSocket = null;
let websocketTimeoutId = null;
// {% if request.protocol == 'https' %} // {% if request.protocol == 'https' %}
let usingWebSockets = true; usingWebSockets = true;
let listenEvents = []; let listenEvents = [];
let wsOpen = false;
/**
* @type {number | null} reconnectorId An interval ID for the reconnector.
*/
let reconnectorId = null;
let failedConnectionCounter = 0; // https://stackoverflow.com/a/37038217/15388424
const wsPageQueryParams = 'page_query_params=' + encodeURIComponent(location.search)
const wsPage = 'page=' + encodeURIComponent(location.pathname)
const sendWssError = () => wsOpen || warn(
'WebSockets are required for Crafty to work. This websocket connection has been closed. Are you using a reverse proxy?',
'https://docs.craftycontrol.com/pages/getting-started/proxies/',
'wssError'
)
function startWebSocket() {
console.log('%c[Crafty Controller] %cConnecting the WebSocket', 'font-weight: 900; color: #800080;', 'font-weight: 900; color: #eee;');
try { try {
pageQueryParams = 'page_query_params=' + encodeURIComponent(location.search) var wsInternal = new WebSocket('wss://' + location.host + '/ws/public?' + wsPage + '&' + wsPageQueryParams);
page = 'page=' + encodeURIComponent(location.pathname)
var wsInternal = new WebSocket('wss://' + location.host + '/ws/public?' + page + '&' + pageQueryParams);
wsInternal.onopen = function () { wsInternal.onopen = function () {
console.log('opened WebSocket connection:', wsInternal) console.log('opened WebSocket connection:', wsInternal)
wsOpen = true;
failedConnectionCounter = 0;
if (typeof reconnectorId === 'number') {
document.querySelectorAll('.wssError').forEach(el => el.remove())
clearInterval(reconnectorId);
reconnectorId = null;
}
}; };
wsInternal.onmessage = function (rawMessage) { wsInternal.onmessage = function (rawMessage) {
var message = JSON.parse(rawMessage.data); var message = JSON.parse(rawMessage.data);
@ -82,9 +109,21 @@
console.error('WebSocket Error', errorEvent); console.error('WebSocket Error', errorEvent);
}; };
wsInternal.onclose = function (closeEvent) { wsInternal.onclose = function (closeEvent) {
wsOpen = false;
console.log('Closed WebSocket', closeEvent); console.log('Closed WebSocket', closeEvent);
};
if (!document.hidden) {
if (typeof reconnectorId !== 'number') {
setTimeout(sendWssError, 7000);
}
console.info("Reconnecting with a timeout of", (getRandomArbitrary(0, 2 ** failedConnectionCounter - 1) + 5) * 1000, "milliseconds");
// Discard old websocket and create a new one in 5 seconds
wsInternal = null
reconnectorId = setTimeout(startWebSocket, (getRandomArbitrary(0, 2 ** failedConnectionCounter - 1) + 5) * 1000)
failedConnectionCounter++;
}
};
webSocket = { webSocket = {
on: function (event, callback) { on: function (event, callback) {
@ -104,15 +143,29 @@
console.error('Error while making websocket helpers', error); console.error('Error while making websocket helpers', error);
usingWebSockets = false; usingWebSockets = false;
} }
}
startWebSocket();
// {% else %} // {% else %}
usingWebSockets = false;
warn('WebSockets are not supported in Crafty if not using the https protocol') warn('WebSockets are not supported in Crafty if not using the https protocol')
var webSocket;
// {% end%} // {% end%}
// Managing Connexions for Multi Tab opened to reduce bandwith usage
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
websocketTimeoutId = setTimeout(() => {
webSocket.close(1000, "Closed due to Inactivity");
console.log('%c[Crafty Controller] %cClose Websocket due to Tab not active after 5s', 'font-weight: 900; color: #800080;', 'font-weight: 900; color: #eee;');
}, 5000);
} else {
clearTimeout(websocketTimeoutId)
if (webSocket.getStatus() == WebSocket.CLOSED) {
startWebSocket();
}
}
});
</script> </script>
{% block js %}
<!-- Custom js for this page -->
<script> <script>
$(document).ready(function () { $(document).ready(function () {
let login_opacity_div = document.getElementById('login_opacity'); let login_opacity_div = document.getElementById('login_opacity');