0

I'm trying make a web which provided user for exam.Everyone only have 15 minutes to answer the questions.When user run out of time,system's gonna submit the result to server.But if user close the browser,nothing's gonna happen. So,how to listening the close event of browser in Angular.

Part2

I wanna submit the result when user close the browser or refresh the web.Ketan Akbari's answer helped me.But there is another question.When I refresh the web,I found the system did't submit the result.Then I open the firebug to check network and compare the difference between refresh and manual.

enter image description here

The dark one is manual,and bright one is refresh.I guess the refresh event stop the operation of submit?

Eve-Sama
  • 2,176
  • 4
  • 20
  • 32
  • 1
    Possible duplicate of [Browser Close Event in angular4](https://stackoverflow.com/questions/45993521/browser-close-event-in-angular4) – Simply Ged Apr 03 '18 at 11:07
  • Take a look at [this question](https://stackoverflow.com/questions/37642589/how-can-we-detect-when-user-closes-browser/37642657) – Simply Ged Apr 03 '18 at 11:08

3 Answers3

3

You can use:

Javascript:

window.onbeforeunload = function (e) {

};

Angular (typescript)

@HostListener('window:beforeunload', ['$event'])
 beforeunloadHandler(event): void {
  // do whatever....
 }
Ketan Akbari
  • 10,837
  • 5
  • 31
  • 51
0

You can use onbeforeunload window event.

Efe
  • 5,180
  • 2
  • 21
  • 33
0

Try to use this into your main template file

<div (window:beforeunload)="checkSomething()"></div>

OR

@Component({ 
  selector: 'xxx',
  host: {'window:beforeunload':'checkSomething'}
  ..
)}

OR

@Component({ 
  selector: 'xxx',
  ..
)}
class MyComponent {
  @HostListener('window:beforeunload')
  checkSomething() {
  }
}

This is the listener behavior.

You can still use

export class AppComponent {  
  constructor() {
    window.onbeforeunload = function(e) {
      return 'You have some unsaved changes';
    };
  }
}

Like explained here https://developer.mozilla.org/de/docs/Web/API/WindowEventHandlers/onbeforeunload

Is there any lifecycle hook like window.onbeforeunload in Angular2?

Shohel
  • 3,886
  • 4
  • 38
  • 75