Is it guaranteed that ajax will execute during beforeunload event?

I am developing an HTML5 application and I need to send a disconnect ajax request when the user changes or refreshes the page. Currently, I have implemented this code:

window.addEventListener("beforeunload", function(event) {
    $.ajax({
        url: api_disconnect,
        data: { identifier: token },
        method: "GET"
    });
});

It is not necessary for me to process the response or ensure that the browser receives it. My main concern is whether I can trust that the server will receive the request.

If not, what is the best approach for achieving this? At the moment, my solution involves sending an "I'm alive!" request every 15 seconds (which may be excessive). Ideally, I would like the server to be immediately notified when the user disconnects.

To clarify, I understand that in cases where the browser or computer crashes, there is not much that can be done. This is why I have implemented the heartbeat mechanism. My question specifically relates to normal use cases when the user purposely closes, changes, or refreshes the page.

Answer №1

It's not a sure thing that the ajax call will always go through. Testing across various browsers and operating systems can give you an idea of which ones usually send the call before the page is taken down, but there's no guarantee it will work according to any set standard.

The heartbeat method, like the one you're using, is a common workaround. It helps in cases of network loss, power failure, computer sleep mode, or browser crashes - situations where the beforeunload handler might not be reliable.

An alternative solution I've come across is utilizing a socket.io connection to the server. With its efficient heartbeat and ability for the server to detect when the socket closes, this method offers a balance between recognizing abnormal shutdowns through the heartbeat and quickly detecting normal shutdowns by observing the closure of the webSocket connection.

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

Which library does stackoverflow utilize to showcase errors (utilizing Bootstrap popover for error help-block)?

Currently, I am using bootstrap's has-error and help-block classes to display validation error messages in my form. However, I find the error message display in Stackoverflow's Ask Questions Form to be very appealing. Are they using a specific js ...

Filtering custom posts in ACF by a specific subfield within a repeater group

I've been trying to implement the tutorials from the ACF documentation, but I'm having trouble getting it right. My setup includes Advanced Custom Fields and Custom Post Type UI plugins. Specifically, I have a custom post type called materials, ...

Modifying the State array is beyond my control

I'm facing an issue passing the codes correctly here, so I'll explain the problem using images. (REMEMBER: All these are within the same component) Issue: I have a single state value: state = { base: [ {tomato: false}, {egg: true} ], ...

Deciphering the AngularJS Component Hierarchy and Managing Identifiers for Freshly Generated Objects (using HTTP)

In my project using Angular 1, I have developed a todo list application which consists of two components. The first is a smart (container) component responsible for server-side interactions, while the second is a dumb/pure/stateless presentation component ...

The Node gracefully disconnects and apologizes: "I'm sorry, but I can't set headers after they have already

events.js:160 throw er; // Unhandled 'error' event ^ Error: Can't set headers after they are sent. register.js:20:18 register.js user.save(function(err) { if(err){ return mainFunctions.sendError(res, req, err, 500, ...

The Express application seems to load forever after a certain period of time

I encountered a peculiar problem with my express application. It was deployed on the server and functioning properly, but after a few hours, when I tried to access the website again, it kept loading indefinitely. Below is my app.js code: const express = r ...

Scope isolation prevents variables from being accessed in higher levels of the scope chain

In my search for answers, I came across some similar questions on SO: Isolate scope variable is undefined unable to access rootscope var in directive scope However, my question presents a unique scenario. I am facing an issue with a directive that has a ...

Converting Roman Numerals into Decimal Numbers using JavaScript Algorithm

I am eager to develop a Javascript Algorithm that can convert Roman numerals to Arabic using the provided methods below. Array.prototype.splice() Array.prototype.indexOf() Array.prototype.join() I have managed to find an algorithm that accomplishes this ...

Issues with jQuery Ajax Request Parsing JSON Data in Internet Explorer

My code is working perfectly with ajax jQuery call to json, except for IE. jQuery.ajax({ url: "/session/json.php", type: "GET", data: "", success: function(data) { var obj = jQuery.parseJSON( ...

Changing a "boolean bit array" to a numerical value using Typescript

Asking for help with converting a "boolean bit array" to a number: const array: boolean[] = [false, true, false, true]; // 0101 Any ideas on how to achieve the number 5 from this? Appreciate any suggestions. Thanks! ...

What causes the function to return null when using router.get('/:x',..), whereas router.get('/foo/:x',...) works perfectly fine?

After weeks of struggling to identify the root cause of my issue, I finally pinpointed it. Now, I'm curious to understand the reason behind this behavior. I constructed an api for my mongodb server following the techniques I learned in school, utiliz ...

Storing form data in a JSON file using JavaScript

For a while now, I've been pondering over this issue. My plan involves creating a desktop application with Electron. As a result, I am working on an app using Node.js and Express.js. The project includes a simple app.js file that executes my website&a ...

Execute the getJSON calls in a loop for a count exceeding 100, and trigger another function once all

In order to process a large grid of data, I need to read it and then make a call to a $getJSON URL. This grid can contain over 100 lines of data. The $getJSON function returns a list of values separated by commas, which I add to an array. After the loop fi ...

Sending reference variable from Angular input type=file

I am currently learning Angular and I have implemented a feature where a list of PDF files is displayed using an array called pdfs. In my template, these PDF files are parsed into "card" elements for better visualization. The issue arises when I attempt ...

Conceal the cursor within a NodeJS blessed application

I am struggling to hide the cursor in my app. I have attempted various methods like: cursor: { color: "black", blink: false, artificial: true, }, I even tried using the following code inside the screen object, but it didn't work: v ...

Locate the parent and child elements within an array

Within the array provided below, there are parent items as well as children. I am currently able to identify parents (depth 0) and their immediate children (depth 1), however I am unsure how to handle deeper nested levels. For reference, you can view the ...

What is the best way to ensure that my grid remains contained within its designated area?

I need to incorporate a grid of 16x16 or 64x64 into my layout without it overflowing. I'm considering using flexbox, but unsure of the implementation process. My goal is to have the grid resize based on the container size rather than exceeding its bou ...

Adjusting the amount of rows and columns in a fluid manner with CSS grid (updated)

After conducting my research, it seems that the most effective way to set the final value of a CSS grid is either by directly specifying it or by creating/manipulating the css :root value. A similar query was previously raised here, although the answers p ...

Struggling to integrate Material UI (MUI) into my React application

I have followed all the necessary steps to install materialUI, emotion/react, and emotion/styled in my react app. However, I am encountering an issue where MUI does not seem to work properly. There are no errors displayed on the console or webpage, but not ...

Stop Carousel when hovering over individual items (Owl Beta 2)

After creating a unique navigation that is separate from the carousel, I encountered some issues with the autoplay feature. Below is the HTML markup: <div class="carousel"> <div class=""> <img src="assets/img/carousel1.jpg" /&g ...