Stop the page from unloading before the ajax request is made

Seeking a solution similar to this question: Reliably complete Ajax request on page unload

I am in need of triggering a network request before the page closes without requiring the response value. However, simply placing it within my beforeunload handler does not achieve the desired outcome:

window.addEventListener('beforeunload', () => {
  // send ajax
}

While it works effectively with sendBeacon, I am looking for a cross-browser compatible solution as sendBeacon may not be supported in all browsers.

Answer №1

There isn't really a perfect solution for this issue. Many makeshift solutions can be found online, some of which are mentioned in the MDN sendBeacon article. Your best option is to use sendBeacon if it's available and have an alternative plan in case it's not.

If you're looking for a quick fix, you can try using this polyfill that performs a synchronous ajax request when sendBeacon is not supported: https://github.com/miguelmota/Navigator.sendBeacon

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

What is the best way to incorporate lottiefiles for a loading animation on a Next.js project's landing

Is there a way to incorporate the use of lottie in a Next.js project (App Structure) in order to load an animated logo seamlessly? I attempted to include "use client" without success, and also tried importing Lottie from react-lottie as a dynamic import. ...

Tips for identifying and logging out a dormant user from the server side using Angular 2 Meteor

I'm currently diving into Angular 2 Meteor and working on a project that requires logging out the user when they close their browser window. I also need them to be redirected to the login page when they reopen the app. After searching online, I could ...

Tips for streamlining the array filtering process

Is there a way to simplify the code to avoid repetitive use of lowercase and includes condition for each property? items() { return this.table.filter.keyword ? this.dataArray.filter( item => item.nombre.toLowerCase().includes(t ...

Tips for accessing the parent window from child windows after navigating to a new link

Starting from a main window, I open a pop-up window (the child) with the following code: onclick=window.open('child_windows.html','popup','width=600,height=300') The child window has a cool feature - it can update the parent ...

Extract the date component exclusively from a REST request on Sharepoint 2013, omitting the time information

I have a date field on a Custom List. The format of that field can be adjusted on the Edit Column Page and it correctly displays only the date on my Custom List page. However, when I try to create a REST query using ajax and output it to the console log fo ...

retaining the scroll position of a window when refreshing a div

There's this issue that's been bothering me lately. I update the database via an ajax call, refresh the div, everything works fine, but it still scrolls to the top of the page. Here's what I have attempted: function postdislike(pid, user, ...

Retrieve the red, green, and blue components of a color in the RGB format

When I retrieve "rgb(18, 115, 224)" from a DOM element, I need to convert this color to hexadecimal in order to assign it to a span element. To get the hexadecimal equivalent of the color, I can use the following code snippet: "#" + componentToHex(r) + co ...

In an AngularJS application, when using fullPage.js on the homepage, it is recommended to ensure that it is

Within my angularJs application, I have implemented fullPage.js on the homepage exclusively to ensure no interference with other pages or routes. To make this possible, I am currently triggering a destroy action during the locationChangeSuccess event. I a ...

Using the `scrollIntoView()` method to continuously scroll through elements in Puppeteer

My goal is to extract a list of posts while the page is continuously loading. I am using scrollIntoView() for each element within a loop. Currently, my code looks like this temporarily. When the page loads, the result bounces out without any errors. for (l ...

Try employing an alternative angular controller when working with the bootstrap modal

I am trying to implement a bootstrap modal in my main HTML file, and I need some help on how to call another Angular controller for the modal. The button that triggers the modal is within a div that already has an Angular controller, and this is causing th ...

The XML string in ajax data is consistently coming back as empty

Whenever I send an xml data string to the server side, it always registers as empty, causing issues. Here is a snippet of my code: $(document).on('click','#metadataListTable .delete', function () { / var ans = confirm("Do ...

Issue with breakpoints functionality in MUI v5 and React project

I've been attempting to utilize breakpoints for responsive design on my website, but unfortunately, it doesn't seem to be working correctly. Every time I implement a breakpoint, the entire page goes blank. Below is the code snippet I am working w ...

Unpredictable order of replies retrieved using $http.get

I am struggling to create a function that sends multiple requests to the server based on the number of Ids in the idArray. The issue I am encountering is that the data being pushed into the dataArray does not align with the corresponding Ids of the idArr ...

Issue with ngModel being undefined after data has finished loading in Ionic 3

As a newcomer to Angular 4, I've been struggling to find a solution for a seemingly simple issue related to an Ionic app. Whenever a user logs in, the entire user object is saved to localStorage. Despite trying various plugins, I settled on a straight ...

two occurrences of the identical controller in AngularJS

Encountering a dilemma (admittedly, not the best approach). There is a single view featuring a split screen; an input field occupies the left side while its corresponding value appears on the right. Both sides are managed by the same controller, using the ...

Angular.js controller unable to receive object array from $http.get in factory

I am fairly new to Angular development and I've hit a roadblock that's been holding me back for a while. My factory is successfully creating an array filled with objects, specifically RSS feed data, and I can see it loading in the console. Howev ...

This route does not allow the use of the POST method. Only the GET and HEAD methods are supported. This limitation is specific to Laravel

I am encountering an issue while attempting to submit an image via Ajax, receiving the following error message: The POST method is not supported for this route. Supported methods: GET, HEAD. Here is the Javascript code: $("form[name='submitProfi ...

Running a 2D JavaScript game script on a React page - A step-by-step guide!

I am facing a challenge with my website that features a game coded entirely in javascript. Despite my efforts to switch the site from an HTML layout to a more modern React design, I can't seem to get the game to display correctly. In the original HTM ...

Verifying that utilizing a factory is the most effective method for developing a versatile click count listener

In my quest to enhance the functionality of click events, I have devised a click count factory. This factory creates a clickCountObj to keep track of the number of clicks and implements a new function for capturing click events on a specified element and r ...

The data received from the frontend is being replicated in the backend, causing duplication issues in a React

Whenever I click the button labeled onClick, it triggers the transmission of data (both time and ID) to the backend. The issue at hand is that the backend seems to be receiving the data twice instead of just once. On inspecting req.body, it becomes eviden ...