2

I have a problem with window event beforeunload in Angular app. i wants to check if the user navigate to another page, if so i want to clean sessionStorage. I use.

   onBeforeUnload(event: BeforeUnloadEvent) {
       event.returnValue = '';
   }

Beforeunload event also workd as a page refresh. How to check if the user leaves the application and clear the sesion storage after confirm dialog.

Cylo
  • 33
  • 1
  • 1
  • 5
  • session storage means it will be auto cleared if he leaves your application means closing a tab or redirected to another website etc – shashi kumar Jan 28 '20 at 07:48
  • If i use back navigate browser buttons, i have previous session :( and it is all my problem – Cylo Jan 28 '20 at 08:14

2 Answers2

3

You can try below code in constructor of your component class.

Option 1

window.addEventListener("beforeunload", function (e) {
   exampleService.logout();
});

Option 2

 @HostListener('window:beforeunload', ['$event'])
     beforeUnloadHandler(event: any) {
     event.preventDefault();
     // any other code / dialog logic
 }

To distinguish from 2 cases, you should check out this stackoverflow question or related questions, here's one:

Question

Hope, this helps.

Hope
  • 475
  • 6
  • 16
  • but I don't want to end the user session if you refresh the application and only if it goes to another page. How to distinguish actions – Cylo Jan 28 '20 at 08:54
  • 1
    You know why performance.navigation.type return type reload if i navigate to another page :( – Cylo Jan 28 '20 at 09:22
  • @Cylo check this: https://stackoverflow.com/questions/7162300/how-can-i-detect-when-the-user-is-leaving-my-site-not-just-going-to-a-different – Hope Jan 28 '20 at 09:26
  • I opened link _blank. I need cheek if user write url in url bar or use tabs. Thanks for help – Cylo Jan 28 '20 at 09:40
  • I dont resolve my problem. performence.navigation.type return type reload all time :( your link no fix my issue. – Cylo Jan 28 '20 at 09:55
  • Okay, you can put a confirmation dialog in onbeforeunload event – Hope Jan 28 '20 at 09:57
  • I can't. If I use beforeunload and method event.preventDefault(), browser return me confirm dialog, i cant customize and I don't know what the user clicked in the dialog. – Cylo Jan 28 '20 at 10:07
  • @Cylo can you check on `canDeactivateGuard` concept in angular. That is for the purpose you are talking about. – Hope Jan 28 '20 at 10:12
  • whether the router detects external navigation? – Cylo Jan 28 '20 at 11:07
  • Yes that. @Cylo – Hope Jan 28 '20 at 11:09
  • Angular router does not detect the transition to another page, but only navigations inside the app. :( – Cylo Jan 28 '20 at 13:34
  • https://stackoverflow.com/questions/147636/best-way-to-detect-when-a-user-leaves-a-web-page Have a look at it. – Hope Jan 29 '20 at 04:01
0

The following code will make browser to ask user that whether he wants to lose the unsaved changes or not.

Also, I'm checking whether the form is dirty or not.

If the form is not dirty, browser won't bother the user and close it.

import { Component, ViewChild, HostListener } from '@angular/core';
import { NgForm } from '@angular/forms';
import { DetailedUser } from 'src/app/models/detailed-user';

@Component({
  selector: 'app-member-edit',
  templateUrl: './member-edit.component.html',
  styleUrls: ['./member-edit.component.css']
})
export class MemberEditComponent {
  user: DetailedUser = new DetailedUser();
  @ViewChild('userForm') userForm: NgForm;
  @HostListener('window:beforeunload', ['$event'])
  WindowBeforeUnoad($event: any) {

    if (this.userForm.dirty) {
      $event.returnValue = 'Your data will be lost!';
    }
  }
  saveChanges(){
    ....
    this.userForm.reset(this.user);
  }
}

the following is the html section

     <form (ngSubmit)="saveChanges()" #userForm="ngForm">
        <div class="form-group">
          <label for="introduction">Introduction</label>
          <textarea
            name="introduction"
            class="form-control"
            [(ngModel)]="user.introduction"
            rows="6"></textarea>
        </div>
        <div class="form-group">
          <label for="lookingFor">Looking For</label>
          <textarea
            name="lookingFor"
            class="form-control"
            [(ngModel)]="user.lookingFor"
            rows="6"></textarea>
        </div>
      </form>
Mehmet Recep Yildiz
  • 1,359
  • 17
  • 14