The back button in the Chrome browser fails to trigger a page refresh within an Angular application

The code snippet above was used in an attempt to refresh the page when the back button is pressed, but it only works inconsistently in Chrome. The issue seems to be that despite correctly detecting the back button press, the page does not always refresh as intended. This problem occurs mainly in a production environment, while occasionally working fine locally.

@HostListener('window:beforeunload', ['$event'])   onPopStateBack() {     
   console.log("Back Button detected!");     
   window.location.reload();  
}   

@HostListener('window:popstate', ['$event'])   onPopState(event: any) {     
   console.log("Back Button detected!");     
   window.location.reload();   
}

Answer №1

If you're looking for a more 'Angular' approach, I suggest utilizing Angular's Router Service. Simply inject the Router Service in your constructor and subscribe to its events. By checking the navigationTrigger property for the 'popstate' event, you can easily detect when the back button is pressed.

constructor(private router: Router){}

ngOnInit(){
   this.refreshOnBackButtonClick();
}

refreshOnBackButtonClick(): void {
   this.router.events.subscribe((event: NavigationStart) => {
     if (event.navigationTrigger === 'popstate') {
       console.log('popstart');
       window.location.reload();
     }
   });
}

Keep in mind that this subscription will also trigger when the forward button is clicked. You may need to distinguish between these events if you only want to refresh on back button clicks. Additionally, explore other properties in the event object to help you make this determination.

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

Using Typescript with Material UI Select

I have implemented a dropdown menu using Material UI select labeled "Search By." When the menu is clicked, it displays a list of options. I aim to store the selected option and update the label "Search By" with the chosen option. export default function U ...

What is the proper way to define a generic function that accepts a Union type as an argument?

I am dealing with various types and their unions. Here is the code snippet: type A = { name: string } type B = { work: boolean } type AB = A[] | B[] const func = (): AB => { return [{ name: 'ww' }] } const data = ...

typescript declaring a namespace with a restricted identifier

I have created a custom Http client in typescript with the following definition: declare namespace Http { type HttpOptions = ...; type HttpPromise<T> = ... function get<T>(url: string, options?: HttpOptions): HttpPromise<T>; ...

Step-by-step guide on integrating StyleX into your fresh React project

As I delve into my new project, incorporating StyleX has proven to be a bit challenging especially when working with NextJS. I find myself grappling with configuring the "next.config.js" file without causing conflicts with the existing "babel.config.js" f ...

What is the best way to preserve the information from the previous page when returning to it after visiting a new one?

My current setup involves 4 components, each with a 'next' button (except the last) and a 'previous' button (except the first). When I click on the Next button, it takes me to the following component. However, when I navigate back to th ...

Issues with loading SourceMap in DevTools after upgrading from Bootstrap 3 to 4

I am currently working on a project with Angular 6 and .NET MVC where I am in the process of upgrading from Bootstrap 3 to Bootstrap 4. Initially, I had been using the Bootstrap 3 CDN and everything was working smoothly. However, I recently had to switch t ...

Do I need to use Node.js for Angular 2, or can I run it on an Apache server instead

Can XAMPP or Apache be used instead of the Node.js npm server when working with Angular 2? ...

The attribute specified is not present on the element within the array

I'm attempting to create an array that includes an object with initialized properties and a number. Yet, I encounter this error message: The error states: 'Property 'foo' does not exist on type 'number | IObj'. The proper ...

Is there a way to package extra files along with `NodejsFunction` in Node.js?

I am looking to add another HTML file to the source code, like shown below. https://i.sstatic.net/OyxDM.png Here is my current code: const mailerFunction = new aws_lambda_nodejs.NodejsFunction(this, 'ApiNotificationHandler', { runtime: lambd ...

Monitor the change in values upon pressing the submit button on Angular

I am currently working with an edit form that contains data in the input fields. <ng-form #infoForm="ngForm" novalidate> <div> <label for="firstName">First Name :</label> <input type=" ...

Exploring the depths of nested JSON with Angular2

I'm a beginner in Angular 2 using Typescript. I am trying to figure out how to access the 'D' and 'G' elements in my JSON data using NgFor. Is there a specific way or method that I can use to achieve this? [ { "A":"B", "C" ...

Compilation with Webpack and Postcss failed due to the inability to locate the scss file within the library in node_modules

Here is the layout of my project structure: node_modules dist config - webpack.common.js - webpack.dev.js - webpack.prod.js - webpack.test.js src - app - app-routing.module.ts - app.component.html - app.component.scss - app.compo ...

Different Option for Single-spa

We currently possess a vast enterprise application developed in angularjs. However, we are now faced with the task of transitioning to angular. Consequently, we have dismissed the option of employing the recommended "ngUpgrade" hybrid approach. Hence, we ...

Retrieve predefined values from a TypeScript controller in Stimulus using the default Symfony configurations

Currently, I am delving into the realm of Stimulus using a standard Symfony6 and Encore setup, with the only notable difference being my use of Typescript. As per the guidance in the Stimulus documentation, typed values should be utilized in the following ...

Typescript is failing to infer the definition of an object, even after conducting a thorough check

I am encountering an issue with the code structure below: interface Data { isAvailable: boolean; } const foo = (data: Data | undefined, error: boolean) => { const hasError = error || !data; if (!hasError) { if (data.isAvailable) // do so ...

Is the validity of the expression !args.value || args.value.length true?

After analyzing this segment of code, I noticed an interesting expression: !args.value || args.value.length For instance, consider the following scenario: let v = {}; console.log(!v.value); //outputs true console.log(v.value); //outputs undefined con ...

Increase by 30 minutes from the minimum value and decrease by 30 minutes from the maximum value in Ionic date time

Looking to add a customized Ionic date time picker with min and max capabilities. If the minimum time is selected, it should automatically add 30 minutes, while selecting the maximum time should subtract 30 minutes. Any suggestions on how to achieve this? ...

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

Similar to Java method references, TypeScript also provides a way to reference functions

Although I am familiar with Java, TypeScript is fairly new to me. In Java, lambda expressions (->) or method references (::) are commonly used to satisfy functional interfaces. It seems like lambda expressions function similarly in both languages (plea ...

What causes the "node: bad option" error to occur when I include a custom flag in the nodejs command line within an Angular 9 application?

Seeking assistance with adding a custom flag to the npm start command in an Angular 9 project. The goal is to intercept proxy requests within the local server and manipulate data. However, encountering the "node: bad option" error consistently. Looking for ...