I'm looking for a client-side JavaScript library that can queue AJAX requests and also support storage. Can anyone recommend

Currently seeking a JavaScript client-side library that can manage a queue of Ajax or WebSocket requests with the following features:

  • Request transmission when the user is online and the server is operational
  • Request storage when the user is offline or the server is unavailable by utilizing local storage
  • Sending stored requests once the user is back online and the server is accessible

Preferably:

  • No reliance on jQuery
  • In addition, I am interested in a complementary server-side component

I have not come across any existing solutions that fit this criteria. Should I take on the task of building one myself using local storage, window.navigator.onLine, and Socket.io, or is there a library available for this specific purpose?

Many thanks.

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

No Response Received from AJAX $.get() Request

I am attempting to implement ajax functionality for the first time in my WordPress theme. After researching the syntax and how it works, I wrote a script that seems to be executing properly but is not returning any response. Using $.get for the Request $ ...

Retrieving data from a material-ui Button component in a React application

I'm currently working with a function that looks like this: handleChangeButton = (e) => { alert(e.target.value) this.props.setFieldValue('degreeLevel', e.target.value); } Within my component's render function, I have the ...

The issue of basic authentication failing to function on Internet Explorer and Chrome, yet operating successfully on Firefox

Here is how my authentication code looks: public class BasicAuthenticationMessageHandler : DelegatingHandler { private const string BasicAuthResponseHeader = "WWW-Authenticate"; private const string BasicAuthResponseHeaderValue = "Basi ...

What is the best way to format or delete text enclosed in quotation marks within an anchor tag using CSS or JavaScript?

I have encountered an issue with a dynamically generated login form. When I select the 'Forgot Password' option, a new 'Back to Login' message appears along with a separating '|' line. Removing this line is proving challenging ...

Elements Fail to Display After Updating State with UseState

This question presents a challenge due to its complexity, but I will try to clarify the situation before delving into the code implementation. My aim is to create a screen for managers displaying all their drivers with minimal information and an edit butto ...

Unable to retrieve the complete count of invitations made by a user

My goal is to retrieve the invites of the author of a specific command within one server. I have experimented with various solutions, but many appear outdated or incorrect. Here is my current approach: exports.run = async (client, message, args) => { ...

Retrieve all data with the same attribute name in one statement from the ajax call

After making an Ajax call, I receive the following data, which includes two images but the number of images can vary: [{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/1.png"}, {"BadgeImag ...

What is the best way to retrieve dynamic content from a .txt file and have it displayed on multiple HTML pages as they are loaded dynamically?

I have a file named 'm_data.txt' stored on the server that contains a continuous total of 77 (for instance). The total gets updated via a push.php page that writes to the .txt file. <!DOCTYPE html> <html> <head> <title> ...

Generating a menu in one-hour intervals

Could someone please advise on the best approach to generate a markup like the one below using Angular: <select> <option value="0000">00:00AM</option> <option value="0100">01:00AM</option> <option value="0200" ...

Encountering the error message "The getStaticPaths function in Next.js requires the 'id' parameter to be provided as a string"

Having an issue with the getStaticPaths function. Every time I attempt to create a dynamic display using a parameter, it gives me an error message: A required parameter (id) was not provided as a string in getStaticPaths for / movies / [id]. However, if ...

Is there a way to programmatically display an edit text field on an HTML page?

Currently, I have a straightforward task which involves pulling data from a MySQL database to display in an HTML table. Here is the current script: <html> <body> <table border='1'> <?php mysql_connect('url',&ap ...

Using Bootstrap Modal with Jquery: Detected 2 elements on the DOM that share the same id, but thankfully all IDs are distinct

I have integrated Bootstrap 4 into my website, and I am facing an issue with having two different modal types on a single page. I am using Ajax to populate the content of these modals, and while the forms in each modal are distinct, they share some similar ...

How can we stop a form from being submitted when the input field is

Similar Question: How to prevent submitting the HTML form’s input field value if it empty <?php include '../core/init.php'; if(isset($_POST['nt']) && isset($_POST['ntb'])){ mysql_query("INSERT INTO `pos ...

Display outcome prior to completion of the website processing in http/html/ajax

I am currently exploring ways to display a wait message in a web application while a task is running for an extended period of time. I am struggling with whether it is even possible. The issue seems to be that the website will only return to the user&apos ...

Navigational bar with React and Next.js. Issue: Hydration unsuccessful due to inconsistencies between the initial UI and the server-rendered content

I am working on a project with Next.js and React. I've created a navbar component but I keep encountering the following error message multiple times: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warni ...

The exported JSON file from the editor is malfunctioning

After importing the obj file into the editor and exporting the geometry to a js file, I encountered an error in Firefox debug saying "Type Error: t1 is undefined". Interestingly, when I changed the model to the .js file exported by MaxExporter with both "E ...

Continuously performing a task in Node.js every 2 minutes until a JSON file, which is being monitored for changes every few seconds

In order to modify a process while my program is running, I need to manually change a value in a .json object from 0 to 1. Now, I want the program to: periodically check the .json file for changes. refresh a browser page (using puppeteer) every 2 minutes ...

Tips for utilizing console log within a react form component

I'm currently exploring ways to communicate with a React form in order to provide it with an object.id for updating purposes. While I can successfully console log the object.id within the update button and modal, I am struggling to confirm if the val ...

Event for updating a cursor in Mongo/Meteor

I am working on developing a chat application using Angular/Meteor technology. Query Is there a method to identify when changes occur in the MongoDB Cursor? Is there an event that gets triggered when a new row is added? When I send a message to another ...

The function image.getState is not recognized (when trying to implement ol in an Angular project)

I attempted to integrate the code provided in an angular(4) application at the following link: However, I encountered an error every time I tried to launch the browser. To start with, here are my imports (both libraries were locally installed via npm): ...