Execute Function Before Browser Refresh in Angular 6/7/8

In this quick post, I show you how to trigger the event to execute a function before the browser refresh in Angular 6/7/8.
The refresh of the page should trigger the event handler bound to a window:beforeunload.
Requirement: Some time we need to store JavaScript object into browser localStorage before browser refresh and then after a browser refresh the data will be retrieved from localStorage into a JavaScript object.
We use @HostListener decorator that declares a DOM event to listen for and provides a handler method to run when that event occurs.

Execute Function Before Browser Refresh in Angular 6/7/8

Refer below snippet and use in your Angular project:
import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements {

  myValue = "Hello world!"

   // call this event handler before browser refresh
  @HostListener("window:beforeunload", ["$event"]) unloadHandler(event: Event) {
      console.log("Processing beforeunload...", this.myValue);
      this.processData();
  }

  // execute this function before browser refresh
  processData(){

     // store data into local storage before browser refresh
    localStorage.setItem('data', this.myValue);
  }
}

Reference

Comments