Anticipate commitments during onbeforeunload

Is there a way to trigger a $http.get request when the page is closed? I encountered an issue where promises cannot be resolved because once the final method returns, the page is destroyed.

The challenge lies in the fact that onbeforeunload does not wait for promises to resolve. Here is an example of why it does not work:

window.onbeforeunload = function(
    $http.get('http://someth.ing/update-state?page=unloaded').then(function(){
        // This code will never be executed as the promise never gets resolved before the page is unloaded.
    }

}

While synchronous HTTP methods can be used as a workaround, the real question is how to synchronize/wait for promises to resolve in this scenario.

One potential solution could involve implementing something like this:

window.onbeforeunload = function(){
    var ready = false;

    $http.get('http://someth.ing/update-state?page=unloaded').then(function(){
         ready=true;
    }

    // The only way I see to sync a promise here is through this loop:
    while(!ready) angular.noop();
    // The big question: has the $http call been made to the server now? Can we safely return from this method and allow the browser to exit the page?
}

RFC

Answer №1

Two issues are currently presenting themselves:

  • The callback being used as a "last-chance" event handler may not be suitable for long-running operations, as browsers handle it differently and the standard operation workflow resumes after the callback exits.
  • Asynchronous operations may not have enough time to finish, especially if they are scheduled to run in the next tick (such as promises).

To address these limitations, there are a few options available:

  • Avoid using asynchronous code and fetch data before reaching this point to use synchronously within onbeforeunload.

  • Utilize ServiceWorker to continue tasks after the page is closed. It is recommended to set up the worker beforehand and communicate with it during onbeforeupload using postMessage. However, keep in mind that ServiceWorker is still a draft and may undergo changes.

  • Remember that the worker does not have direct access to the page, which means no window object or loaded libraries. Data exchange must be done through explicit messages only.

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

Steps to isolate the "changed" values from two JSON objects

Here is a unique question that involves comparing JSON structures and extracting the differences. A JqTree has been created, where when the user changes its tree structure, both the "old" JSON and "new" JSON structures need to be compared. Only the values ...

The hover effect is not functioning properly after loading jQuery with load();

When loading elements into a div using the load() function, I noticed that the :hover effect in CSS stops working for those elements. It's a dynamic menu setup, as shown below: <div id='main-menu'> <ul> <li class='click ...

Error Message: Attempting to access the AngularJS injector before it has been initialized

Using AngularJS Service in an Angular 5 Component I have an existing AngularJS application and I am attempting to create a hybrid app. However, I am encountering difficulties using an AngularJS service within an Angular component, resulting in the followi ...

Interactive div containing elements that cannot be clicked

http://codepen.io/anon/pen/zxoYBN To demonstrate my issue, I created a small example where there is a link button within a div that toggles another div when clicked. However, I want the link button to not trigger the toggle event and be excluded from the ...

Error: Module not located in Custom NPM UI Library catalog

I have recently developed an NPM package to store all of my UI components that I have created over the past few years. After uploading the package onto NPM, I encountered an issue when trying to use a button in another project. The error message "Module no ...

Establish the editor's starting state

Currently, I am utilizing lexical and aiming to establish initial text for the editor. At the moment, my approach involves hardcoding the initial text, but it seems I cannot simply pass a String as anticipated. Instead, the format required is JSON. Hence ...

Move the JavaScript code from the <script> element in the HTML file to a

Recently, I've been exploring the idea of incorporating a tradingview ticker on my website. Trading view has kindly provided me with a snippet to embed into my webpage: <!-- TradingView Widget BEGIN --> <div class="tradingview-widget-co ...

What is the method by which Morgan middleware consistently displays the output on the console following the execution of all other middleware

Utilizing the express library along with the logging library known as morgan Provided below is a snippet of working code that can be used to reproduce this in nodejs: const express = require('express') const morgan = require('morgan') ...

Creating a PNG image on a canvas, converting it to a data URL, and then transmitting it using an XMLHttpRequest in NodeJS/Express

I've been experimenting with different methods found on Google, but so far none have worked for me. I'm currently working on implementing the signature-pad, a JavaScript/HTML5 canvas solution for eSignatures. My goal is to save the canvas data as ...

Click the button to automatically generate a serial number on the form

My form includes three input fields: sl no, stationerytype, and stationeryqty. By clicking the symbols + and -, I can add or delete these fields. I am attempting to automatically generate a Sl no in the sl no field when I click the plus symbol, and adjust ...

What could be the reason that a MUI component does not disappear when the display is set to none in the sx prop?

I'm attempting to construct a responsive side drawer using MUI's Drawer component in React, specifically leveraging MUI version 4.12.1. In the example provided on the mui.com website, they utilize the sx prop and pass an object with different di ...

Refreshing a specific div within an HTML page

I am facing an issue with the navigation on my website. Currently, I have a div on the left side of the page containing a nav bar. However, when a user clicks a link in the nav bar, only the content on the right side of the page changes. Is there a way t ...

Error encountered with the $get method of AngularJS Provider during configuration() function

Recently, I configured a Provider that fetches a language JSON file from a web server and delivers it to Angular within the config() method. Here is the provider setup: .provider('language', function () { var languageWsURL , languageC ...

Issue with resetting Knockout.JS array - unable to make it work

Hey everyone, check out the project I'm currently working on over at Github: https://github.com/joelt11753/Udacity-map In this project, I have a menu generated from a list that can be filtered using an HTML select element. Initially, all items are di ...

Protractor Problem with Asynchronous Calls

New to Protractor, I started by using multiple 'its' in my code. However, I later consolidated everything into one 'it', resulting in the following structure: var UI = require('./../ui.js'); var co = require('co'); ...

displaying outcomes as 'Indefinite' rather than the anticipated result in the input field

I need to automatically populate values into 4 text fields based on the input value entered by the user. When the user exits the input field, a function called getcredentials() is triggered. This function, in turn, executes Python code that retrieves the r ...

Incorporating a <script> tag in Angular 8 to reference an external JavaScript file from a different website

I am currently using Angular 8 and its CLI to develop my website. Issue: I need to include an external JavaScript file from a different website by adding a <script> tag, for example: <script src="https://www.wiris.net/demo/plugins/app/WIRISplugin ...

Enhancing the mobile menu with a feature that allows users to easily close the

I am currently designing a mobile menu for a website that I created using Wordpress with the Divi Theme. When the user clicks on a "hamburger icon", it triggers a fullscreen menu to open: mobile menu If you tap on "Termine", it will reveal a submenu: mo ...

Obtaining the name of the image that has been uploaded using jQuery

//Image upload function $(function() { $(":file").change(function() { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = imageIsLoaded; reader.readAsDataURL(this.files[0]); } }); }); function im ...

A thrilling twist on the classic game of Tic Tac Toe, where X and

I am having trouble with switching between the cross and circle symbols in my Tic Tac Toe game. The code seems to be set up correctly, but it's not functioning as expected. Any suggestions on how to fix this? Here is the JavaScript code: varcode va ...