Tips for triggering functions when a user closes the browser or tab in Angular 9

I've exhausted all my research efforts in trying to find a solution that actually works. The problem I am facing is getting two methods from two different services to run when the browser or tab is closed.

I attempted using the fetch API, which worked flawlessly on Chrome but failed to cooperate on Internet Explorer. Another approach I took was implementing a while loop like the one below:

@HostListener('window:beforeunload', ['$event'])
onBeforeUnload(): void {
    var sessionEnded = false;
this.userSessionService.EndSession(this.userSessionId).then(res => sessionEnded = res);;
while (sessionEnded == false) {
  console.log('session not ended');
}
  }

This method was successful on Chrome, however, it didn't quite cut it when trying to close the browser on IE.

Have I missed any other alternative solutions out there?

Could opening a new tab to carry out these functions and then closing upon completion be a feasible option?

Answer №1

@HostListener('window:beforeunload', ['$event'])
async handleBeforeUnload(): void {
    let hasEndedSession = false;
    await hasEndedSession = this.service.endUserSession(this.sessionId);
    while (!hasEndedSession) {
      console.log('Session is still active');
    }
  }

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

Leveraging the power of the map function to cycle through two arrays

Right now in React, I am utilizing array.map(function(text,index){}) to loop through an array. But, how can I iterate through two arrays simultaneously using map? UPDATE var sentenceList = sentences.map(function(text,index){ return <ListGr ...

Setting up a software from a GitHub source

My issue arises when attempting to install a particular package of mine with the version specified as a specific git branch. The problem occurs because the repository does not contain the dist folder, which is required by my npm package. Here is the metho ...

Utilizing TypeScript's higher-order components to exclude a React property when implementing them

Trying to create a higher-order component in TypeScript that takes a React component class, wraps it, and returns a type with one of the declared properties omitted. Here's an attempt: interface MyProps { hello: string; world: number; } interfac ...

Retrieve the HTML representation of a progress bar in Ext JS 3.4 prior to its rendering

Is it possible to obtain the HTML representation of a progress bar before it is rendered anywhere? I am currently using a custom renderer for rendering a progress column in a grid: renderer: function( value, metaData, record, rowIndex, colIndex, store ) ...

Masking input text to allow numbers only using either javascript or jquery

I have experience with javascript and jquery. My goal is to create a masking template for <input type="text"> This template should only accept numbers and automatically format the input with dashes after every two numbers typed. The desi ...

Retrieve element attributes and context inside a function invoked by an Angular directive

When working with a directive definition, you have access to the $element and $attrs APIs. These allow you to refer back to the element that called the directive. However, I'm curious how to access $element and $attrs when using a standard directive l ...

Adding content into a designated position in a document

My challenge is to find the index of user-provided data in order to insert new data at that specific point. I am familiar with array insertion methods, but extracting the index provided by the user is where I'm stuck. My current approach involves filt ...

Error: props.addPost does not exist as a function

Help Needed with React Error: props.addPost is not a function. I am trying to add a new post in my app. Please assist me. import React from "react"; import classes from "./MyPosts.module.css"; import { Post } from "./Post/Post.jsx& ...

Tips for addressing the browser global object in TypeScript when it is located within a separate namespace with the identical name

Currently diving into TypeScript and trying to figure out how to reference the global Math namespace within another namespace named Math. Here's a snippet of what I'm working with: namespace THREE { namespace Math { export function p ...

Element sticking on scroll down and sticking on scroll up movements

I am currently working on a sticky sidebar that catches and stays fixed at a certain scroll point using JavaScript. However, I am facing an issue where I need the sidebar to catch when scrolling back up and not go further than its initial starting point. ...

The power of absolute paths in React Native 0.72 with TypeScript

Hi everyone! I'm currently having some difficulty setting absolute paths in react native. I tried using babel-plugin-module-resolver, as well as configuring 'tsconfig.json' and 'babel.config.js' as shown below. Interestingly, VS Co ...

Exploring the creation of a dynamic graph with d3.js

I'm new to d3 and attempting to create a graph layout. var w = 1000; var h = 500; var dataset = { nodes: [{ name: 'Alice' }, { name: 'David' ...

A guide to organizing elements in Javascript to calculate the Cartesian product in Javascript

I encountered a situation where I have an object structured like this: [ {attributeGroupId:2, attributeId: 11, name: 'Diamond'}, {attributeGroupId:1, attributeId: 9, name: '916'}, {attributeGroupId:1, attributeId: 1, name ...

When an import is included, a Typescript self-executing function will fail to run

Looking at this Typescript code: (()=> { console.log('called boot'); // 'called boot' })(); The resulting JavaScript is: (function () { console.log('called boot'); })(); define("StockMarketService", ["require", "exp ...

Facing a dilemma: Javascript not updating HTML image source

I am facing an issue while attempting to modify the source of my HTML image element. Despite using document.getElementId('image') in my code, I am unable to make it work as intended. Surprisingly, there are no errors displayed. Interestingly, whe ...

When updating the data in a datatables.net table within Angular 7, the previous data from the initial table load is retained

I'm currently working on a project that involves live reporting from a REST API request using the datatables.net library in Angular 7. When I update data in the database, the table reflects these changes accurately. However, if I interact with the tab ...

Using *ngIf in Angular to display a list of items only when the length is greater than 0

<h1>{{title}}</h1> <ul> <li *ngFor="let breed of data.message | keyvalue"> <a [routerLink]="['/picsofbreed']" [queryParams]="{breed: breed.key}" target="_blank">{{breed.k ...

Accessibility issues detected in Bootstrap toggle buttons

I've been experimenting with implementing the Bootstrap toggle button, but I'm having an issue where I can't 'tab' to them using the keyboard due to something in their js script. Interestingly, when I remove the js script, I'm ...

When Controller Scope Goes Missing in ng-repeat

Upon glancing at my code, it should be evident that I am a newcomer to the world of Angular. I am currently developing an application that enables users to search for text, queries a database whenever the value in the text input changes, and displays a li ...

JavaScript's "for of" loop is not supported in IE 11, causing it to fail

Here is a piece of code I'm using to select and remove a d3.js node: if (d.children) { for (var child of d.children) { if (child == node) { d.children = _.without(d.children, child); update(root); ...