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 webSocket = null;
let websocketTimeoutId = null;
// {% if request.protocol == 'https' %}
usingWebSockets = true;
@ -282,18 +283,19 @@
wsOpen = false;
console.log('Closed WebSocket', closeEvent);
if (typeof reconnectorId !== 'number') {
setTimeout(sendWssError, 7000);
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++;
}
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 = {
on: function (event, callback) {
console.log('registered ' + event + ' event');
@ -319,6 +321,21 @@
warn('WebSockets are not supported in Crafty if not using the https protocol')
// {% 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) {
webSocket.on('send_start_error', function (start_error) {
var x = document.querySelector('.bootbox');
@ -509,10 +526,10 @@
document.addEventListener('alpine:init', () => {
console.log('%c[Crafty Controller] %cAlpine.js pre-initialization!', 'font-weight: 900; color: #800080;', 'color: #eee;');
})
});
document.addEventListener('alpine:initialized', () => {
console.log('%c[Crafty Controller] %cAlpine.js initialized!', 'font-weight: 900; color: #800080;', 'color: #eee;');
})
});
$(document).ready(function () {
console.log('%c[Crafty Controller] %cReady for JS!', 'font-weight: 900; color: #800080;', 'font-weight: 900; color: #eee;');

View File

@ -55,64 +55,117 @@
<script src="/static/assets/js/shared/hoverable-collapse.js"></script>
<script src="/static/assets/js/shared/misc.js"></script>
<!-- endinject -->
<script>
// {% if request.protocol == 'https' %}
let usingWebSockets = true;
let listenEvents = [];
try {
pageQueryParams = 'page_query_params=' + encodeURIComponent(location.search)
page = 'page=' + encodeURIComponent(location.pathname)
var wsInternal = new WebSocket('wss://' + location.host + '/ws/public?' + page + '&' + pageQueryParams);
wsInternal.onopen = function () {
console.log('opened WebSocket connection:', wsInternal)
};
wsInternal.onmessage = function (rawMessage) {
var message = JSON.parse(rawMessage.data);
console.log('got message: ', message)
listenEvents
.filter(listenedEvent => listenedEvent.event == message.event)
.forEach(listenedEvent => listenedEvent.callback(message.data))
};
wsInternal.onerror = function (errorEvent) {
console.error('WebSocket Error', errorEvent);
};
wsInternal.onclose = function (closeEvent) {
console.log('Closed WebSocket', closeEvent);
};
webSocket = {
on: function (event, callback) {
console.log('registered ' + event + ' event');
listenEvents.push({ event: event, callback: callback })
},
emit: function (event, data) {
var message = {
event: event,
data: data
}
wsInternal.send(JSON.stringify(message));
}
}
} catch (error) {
console.error('Error while making websocket helpers', error);
usingWebSockets = false;
}
// {% else %}
usingWebSockets = false;
warn('WebSockets are not supported in Crafty if not using the https protocol')
var webSocket;
// {% end%}
</script>
{% block js %}
<!-- Custom js for this page -->
<script>
/* Script for WebSockets */
let usingWebSockets = false;
let webSocket = null;
let websocketTimeoutId = null;
// {% if request.protocol == 'https' %}
usingWebSockets = true;
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 {
var wsInternal = new WebSocket('wss://' + location.host + '/ws/public?' + wsPage + '&' + wsPageQueryParams);
wsInternal.onopen = function () {
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) {
var message = JSON.parse(rawMessage.data);
console.log('got message: ', message)
listenEvents
.filter(listenedEvent => listenedEvent.event == message.event)
.forEach(listenedEvent => listenedEvent.callback(message.data))
};
wsInternal.onerror = function (errorEvent) {
console.error('WebSocket Error', errorEvent);
};
wsInternal.onclose = function (closeEvent) {
wsOpen = false;
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 = {
on: function (event, callback) {
console.log('registered ' + event + ' event');
listenEvents.push({ event: event, callback: callback })
},
emit: function (event, data) {
var message = {
event: event,
data: data
}
wsInternal.send(JSON.stringify(message));
}
}
} catch (error) {
console.error('Error while making websocket helpers', error);
usingWebSockets = false;
}
}
startWebSocket();
// {% else %}
warn('WebSockets are not supported in Crafty if not using the https protocol')
// {% 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>
$(document).ready(function () {
let login_opacity_div = document.getElementById('login_opacity');