Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh.

Below is the code snippet I am currently using:

@HostListener('window:beforeunload', ['$event'])
checkIsUserLogOut() {
    if (ConfigurationModel.applicationOptions.autoLogOutWhenWebBrowserClosed) {
        localStorage.removeItem('auth_token');
        localStorage.removeItem('auth_token_expires_on');
    }
}

Answer №1

Stumbled upon a helpful article addressing this specific issue of not triggering code on page refresh.

The solution involves utilizing a localStorage variable to store the timestamp of the last unload event, determining if it's within a certain timeframe to classify it as a refresh.

The unload event handler is as follows:

function unload(event) {
    if (window.localStorage) {
        // Marking the page as unloading
        window.localStorage['myUnloadEventFlag'] = new Date().getTime();
    }

    askServerToDisconnectUserInAFewSeconds(); // Synchronous AJAX call

}

Upon page load:

function myLoad(event) {
    if (window.localStorage) {
        var t0 = Number(window.localStorage['myUnloadEventFlag']);
        if (isNaN(t0)) t0 = 0;
        var t1 = new Date().getTime();
        var duration = t1 - t0;
        if (duration < 10 * 1000) {
            // Less than 10 seconds since the previous Unload event => it's a browser reload (cancel disconnection request)
            askServerToCancelDisconnectionRequest(); // Asynchronous AJAX call
        } else {
            // Last unload event was for tab/window close => proceed with necessary actions
        }
    }
} 

Hope this method proves useful in handling your scenario.

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

Access a PDF document in a new tab and save it with a specific file name using Angular

I am facing a challenge in Angular where I want to open a PDF file in a new tab and enable the user to download it with a specific name (Example.pdf). The current code successfully downloads the PDF but does not open a new tab (target=_blank is ineffecti ...

Animating sprites using TypeScript

I've been tackling the development of a small Mario game lately. However, I'm facing some difficulty when it comes to animating sprites. For instance, I have a mario.gif file featuring running Mario (although he's not actually running in th ...

Transforming the API response

After making an Ajax call, the response received is: console.log(data); {"valid":true,"when":"Today"} Attempting to read the response like this: var res = data.valid; console.log(res); results in 'undefined' being displayed. To address this i ...

The execution of the start script has encountered an error

Angular: 5.0.1 / Angular CLI: 1.5.0 / Node: 8.9.1 / npm: 5.5.1 / Os: win32 x64 Executed "npm start" in the terminal/command prompt and encountered the following error. I have been struggling to fix it for a whole day with no success. Can anyone assist me ...

Stopping the page from scrolling back to the top when an asynchronous update occurs in Angular

Once the asynchronous request is complete, I dynamically add a new element to the top with this code snippet: Array.prototype.unshift.apply(scope.conversation, conversation.data.message); The issue arises when the added element causes the scroll position ...

Having trouble updating the sequelize-cli configuration to a dynamic configuration

Encountering an issue while attempting to switch the sequelize-cli configuration to dynamic configuration, following the instructions in the documentation. I have created the .sequelizerc-file in the project's root directory and set up the path to con ...

Utilizing jQuery BBQ for Seamless Transitions – From Fading to Sliding and More

This is my first time posting a question here, even though I am an active user of stackoverflow. I have developed a website using jQuery BBQ to load pages through AJAX while still maintaining the ability to track history with the back button and other fun ...

Passing data as a parameter from the view to the controller using AngularJS

I am attempting to retrieve data from a view, which must be passed as a parameter in a function in order to populate an array in the controller. However, I am not receiving any objects in return. Here is what I have tried: VIEW <div ng-repeat="cssfram ...

What is the best way to save the output of a middleware in express js so that it can be conveniently accessed by the rest of the

Currently, I am working with a middleware that returns an object. My goal is to save this object so that other parts of the application can utilize the data it contains. How can I achieve this? This snippet is from my app.js file: import { myMiddlewareFun ...

How can I rectify the varying vulnerabilities that arise from npm installation?

After running npm audit, I encountered an error related to Uncontrolled Resource Consumption in firebase. Is there a solution available? The issue can be fixed using `npm audit fix --force`. This will install <a href="/cdn-cgi/l/email-protection" clas ...

Leverage ngFor multiple times to iterate through the same array

As someone new to Angular and Ionic, I've scoured the internet (including this site) for a solution to my problem without much luck. My goal is to have a single array of tasks in my ts component and display them in four different sections of my html t ...

invoke two JavaScript functions without displaying any message

I'm facing an issue with Ajax as it's not displaying the message I intend to show. Let me elaborate. Within my PHP code, there is an input tag: <input type="submit" id="login_button_add" name="submit" value="Add" onclick="add_building(); sho ...

Exploiting jQuery UI in a Web Browser Bookmarklet

When using CoffeeScript, even though the code is very similar to JavaScript: tabs_html = "<div id='nm-container'><ul><li><a href='#tabs-1'>Guidelines</a></li><li><a href='#tabs-2'& ...

Using jQuery each, the output is an undefined Object or HTMLElement

Using jQuery's each/getJSON to iterate through a data.json file, collect and format the data, and display it on the page within the #output div. The functionality is working correctly, except for the unexpected addition of [object HTMLElement] that a ...

Ways to boost performance in an Angular 6.0 application

https://i.stack.imgur.com/Rq9Y2.jpg We have recently developed a cutting-edge application using Angular 6, hosted on an Apache 2.4 server. To ensure our website is properly crawled by search engines, we set up a local "prerender" instance. Initially, we t ...

The environment production variable is perpetually set to true within the app.module.ts file

I'm currently facing an issue with setting a configuration in my app.module file that should differ based on whether I'm in production or not. Within my environment.ts file, I have the following: export const environment = { production: false ...

Utilizing Axios for Vue Multiselect on select/enter Event

I have successfully implemented a Vue Multiselect feature that retrieves options from my database using an axios call. This functionality works great as it allows users to select existing options or add new ones to create tags. While this setup is working ...

Dynamic controller in TypeScript with React Hook Form

Is there a way to ensure that the fieldName is always inside the control? Passing a field name that doesn't exist in the form causes issues for me, so I'm looking for a solution. Can anyone help? import { Control, Controller } from 'react-ho ...

Extracting information from within Ajax's Jsonp

How can I retrieve data from the Ajax function(result)? Why isn't this app working? Please assist me. function star(a) { var res; $.ajax({ url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35 ...

What is the process for extracting components from a JSON file using an observable in Angular?

Take a look at this snippet of code: response: any; fetchData(url: any) { this.response = this.http.get(url); } ngOnInit(): void { fetchData("url.com/data.json"); console.log(this.response) } When I check the console, I see Obser ...