What is the best way to automatically close a web page if the user does not respond?

Hello Team, I could use some assistance regarding a validation issue.

I am looking for a solution to automatically close my web page if the user does not respond with either "yes" or "no" within 30 minutes.

constructor(private loginService:AuthenticationService,private router: Router) {
          this.setTimeout();
          this.userInactive.subscribe(()=> this.cancel());
      }

      setTimeout() {
        this.userActivity = setTimeout(() => this.userInactive.next(undefined), 300000);
      }

      @HostListener('window:mousemove') refreshUserState() {
        clearTimeout(this.userActivity);
        this.setTimeout();
      }

      cancel() {
        var cancel = confirm("We have detected inactivity. Would you like to continue?");
        if (cancel) {
          return true;
        } else {
          this.router.navigate(['/logout']);
          return false;
        }

  }

Answer №1

Consider implementing local storage for enhanced functionality

import { Injectable } from "@angular/core";
import { Router } from '@angular/router'
const MINUTES_UNITL_AUTO_LOGOUT = 60 // in mins
const CHECK_INTERVAL = 15000 // in ms
const STORE_KEY =  'lastAction';
@Injectable()
export class AutoLogoutService {
 public getLastAction() {
    return parseInt(localStorage.getItem(STORE_KEY));
  }
 public setLastAction(lastAction: number) {
    localStorage.setItem(STORE_KEY, lastAction.toString());
  }

  constructor(private router: Router) {
    this.check();
    this.initListener();
    this.initInterval();
    localStorage.setItem(STORE_KEY,Date.now().toString());
  }

  initListener() {
    document.body.addEventListener('click', () => this.reset());
    document.body.addEventListener('mouseover',()=> this.reset());
    document.body.addEventListener('mouseout',() => this.reset());
    document.body.addEventListener('keydown',() => this.reset());
    document.body.addEventListener('keyup',() => this.reset());
    document.body.addEventListener('keypress',() => this.reset());
  }

  reset() {
    this.setLastAction(Date.now());
  }

  initInterval() {
    setInterval(() => {
      this.check();
    }, CHECK_INTERVAL);
  }

  check() {
    const now = Date.now();
    const timeleft = this.getLastAction() + MINUTES_UNITL_AUTO_LOGOUT * 60 * 1000;
    const diff = timeleft - now;
    const isTimeout = diff < 0;

    if (isTimeout)  {
      localStorage.clear();
      this.router.navigate(['./login']);
    }
  }
}

Answer №2

When implementing the cancel method, it is crucial to remember to reset the timeout once again.

  cancel() {
    var cancel = confirm("It seems like there has been inactivity. Do you wish to proceed?");
    if (cancel) {
      clearTimeout(this.userActivity);
      this.setTimeout();
      return true;
    } else {
      this.router.navigate(['/logout']);
      return false;
    } 

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

Dealing with 'TypeError X is Not a Function' Error in Angular (TypeScript): Occurrences in Certain Scenarios and Absence in Others

Recently, I came across an odd issue in Angular 14 where a type error kept popping up. Although I managed to refactor the code and find a workaround, I'm quite intrigued as to why this issue is happening so that I can prevent it from occurring again i ...

Different ways to convert a date object to instant type in Angular without considering the timestamp

I have a function that converts a Date to a timestamp, but it includes the timezone, which I don't want. I only need the date with no timezone information in Instant type. convertDateToTimeStamp(date: any) { return Date.parse(date) / 1000; } Befor ...

Retrieving information from a JSON file utilizing an Interface

For the purpose of learning, I am developing a small Ionic app where I want to load data from a JSON file and map it to an interface that defines the data structure. However, I am facing challenges in achieving this: import { Component } from "@angular/co ...

Learn how to easily toggle table column text visibility with a simple click

I have a working Angular 9 application where I've implemented a custom table to showcase the data. Upon clicking on a column, it triggers a custom modal dialog. The unique feature of my setup is that multiple dialog modals can be opened simultaneously ...

What is the best way to customize column width in AG-Grid?

I am looking for a way to dynamically set column width in my table. I have provided a stackblitz example which demonstrates that when changing the screen size, only the table border adjusts, but not the column widths. Is there a way to also change the col ...

What are the steps to incorporating the pick function in TypeScript?

The TypeScript documentation mentions a pick function that is declared but not implemented. In an attempt to create a simplified version, I wrote the following: function pick<T, K extends keyof T>(obj: T, key: K): Pick<T, K> { return { [key]: ...

JavaScript/TypeScript - Restricting to only assigned properties in an object

Consider this scenario: Suppose we have an object with the following properties: const objOne = { car: 'ford', location: 'Munich', driver: 'John' } and a second object that only contains some of the properties from th ...

Would it be possible to use the Stripe customer portal to facilitate subscription upgrades or downgrades that take effect at the end of the current billing cycle?

I am struggling to figure out how to manage subscription upgrades and downgrades on the user interface side so that they start at the end of the current billing cycle. The only Stripe-hosted page for handling subscription changes is the customer billing p ...

In the production build, the RegEx validation is lacking and fails to accept certain characters like 0, 2, 7, a, c, u, x, and occasionally z

Incorporating Angular 15.2.10 and Typescript 4.9.5, the RegEx utilized in one of my libraries and exposed via a service is outlined as follows: private readonly _DISALLOWED_CHARS_REGEX_GENERAL = new RegExp(/^[^\\/\?\!\&\: ...

AngularYelp: Node Integration for Enhanced Functionality

Embarking on a new learning journey here, so please bear with me... Discovered node-yelp while browsing Yelp's API docs. Check it out here. // Request API access: http://www.yelp.com/developers/getting_started/api_access var Yelp = require('yel ...

Guide to making a ng-bootstrap modal that retains a component's state

I am currently working on implementing a modal with Angular by following a tutorial on the ng-bootstrap website ( - in the "Components as content" section). However, I am facing a challenge where I want the component displayed in the modal to retain its st ...

What is the proper way to utilize variables in package.json with npm version 7.x.x?

I am looking to utilize npm scripts to access keys found in the directories section. "directories": { "client": "client", "server": "server" }, "scripts": { "test:client&qu ...

Breaking a line within an ngFor loop

I'm working with an ngFor loop to generate multiple PrimeNG buttons. Currently, the buttons are displayed side by side on the same row, but I want each button to appear vertically on its own line. How can this be achieved? Below is the segment of my c ...

What causes NG-REPEAT to malfunction when used with a JSON variable retrieved from a service?

I am trying to create a select dropdown menu in my Angular application by populating it with options from a JSON variable located in my StudentService.ts file. Within my service: careers : {}; constructor(private http: HttpClient) { this.selecte ...

Adding one day to a date using TypeScript

Could someone please explain how to increment a date variable by 1 day in TypeScript? I'm looking for the best way to add a day to a date field in TypeScript. ...

What is the best layer to handle Entity-DTO conversion in my application?

I utilized TypeORM to establish two entities: User and School: @Entity() export class User { // ... @ManyToOne(() => School, school => school.id) school: School; // ... static from( uid: string, name: string, email: string, ...

Is it possible for me to dynamically alter the innerHTML of an input element using

I am working on a small Angular application. One of my components uses innerHTML to display content. <div [innerHTML]="serviceShared.currentMood"></div> However, when I change the value of serviceShared.currentMood in the main component, noth ...

Can TypeScript be imported into HTML to set a color value or modify a color value from HTML using TypeScript?

I've been working on this code for a couple of days now. Utilizing Angular to develop a web application, I am trying to change the color of certain numbers when they reach a specific value. For example, if num > 45 then color = green, otherwise col ...

unable to transform this string into an object

https://i.sstatic.net/O46IL.pngWhy am I encountering difficulties converting this string into an object? Any assistance on resolving this error would be greatly appreciated. onSignup(data:any){ localStorage.setItem('users',JSON.string ...

Prevent special characters from being entered into an HTML input box with Angular 7

I'm looking to limit the use of special characters in an HTML input box using Angular 7. I also need to set requirements for only allowing numbers, letters, etc. As I am new to Angular, any assistance would be greatly appreciated. I've attempte ...