It's possible that the question will be closed as requesting a library is typically discouraged on this platform. Nevertheless, the challenge of creating a solution is quite enjoyable and only took me around 15 minutes to complete.
The task at hand is relatively small, spanning just about 50 lines of code. This could be why a concise library specifically designed for this task may not readily available.
function MessageSender() {
var requests = [],
state = 0; // 0 = closed, 1 = open
ws = new WebSocket();
ws.onopen = function() {
state = 1;
if (requests.length) {
send();
}
};
ws.onerror = function() {
if (ws.readyState !== 1) { // 1 signifies "OPEN"
close();
}
};
// Pre-populate the requests array if needed
// Using an IIFE to avoid scope pollution with `req`
(function() {
var req = JSON.parse(localStorage.get('queue'));
if (req.length) {
requests = requests.concat(req);
}
}());
return {
send: function(msg) {
if (state === 0) {
requests.push(msg);
}
else {
send();
}
},
close: function() {
state = 0;
localStorage.set('queue', JSON.stringify(requests));
}
};
function send() {
var done = false;
while (!done) {
if (state === 1) {
ws.send(requests.pop());
if (!requests.length) {
done = true;
}
}
else {
done = true;
}
}
}
}
// Example of how to use the MessageSender
var messageSender = MessageSender();
messageSender.send('message');
// Assuming your "disconnect" button exists in a variable
disconnect.addEventListener('click', function() {
messageSender.close();
}, false);
The server simply needs to handle regular requests. Optionally, you can append a timestamp to the message being sent, making it easy (just 2 lines or so) to track the time.