Chrome Back button problem arises following interaction with Iframe in Angular

I am currently working on an Angular application that involves a specific process:

  1. Users follow a flow and end up on one of the partial pages.

  2. From this partial page, I trigger a button to fetch an ID from a cross domain using a service call (no CORS issue).

  3. With this ID, I append it to the URL of the cross domain like

  4. This modified URL is then loaded in a child component inside an iframe.

  5. The cross domain's page within the iframe contains 'Save' and 'Cancel' buttons.

  6. Upon clicking either of these buttons, the application navigates back.

  7. However, there is an ISSUE: When users click the 'Chrome browser's back button' after successful navigation, the application reloads.

This causes the entire flow of the application to restart, forcing customers to go through the flow again. Even though the data is updated upon return to the previous partial page, it creates a poor user experience.

Currently, I suspect that the use of DomSanitizer might be causing this strange behavior in Chrome while other browsers work fine.

Here is a snippet of the code used to load the cross domain's URL in the iframe:

constructor(private sanitizer: DomSanitizer) { }

ngOnInit() {
    this.targetUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.sourceUrl);
}

Angular Template:

<iframe #crossDomainIframe [src]="targetUrl" (load)="onPageLoad()">
</iframe>

In the onPageLoad() function, I simply handle the logic of returning the response to the parent component.

onPageLoad () {
    this.callbackResponse.emit(returnUrl);
}

My question is: Is there a way to resolve this issue?

Alternatively, is there a different method for executing the cross domain request in the iframe?

Answer №1

Simply put, dealing with back button presses in web development is an ongoing issue. However, there are a few approaches to consider. First idea: utilize the onbeforeunload event within the window:

window.addEventListener('beforeunload', function(e){
    e.preventDefault();
    e.returnValue = 'Clicking the back button will reset your progress!';
    return e.returnValue;
});

Although not all browsers will display the exact message, setting the returnValue will prompt users before reloading, which is better than nothing. It may also trigger on close or refresh, so remember to remove the listener when done.

Another idea is to set a hash:

var ignoreNextHashChange;
window.onhashchange = function(){
  if (ignoreNextHashChange)
    ignoreNextHashChange = false;
  else
    alert('Hold up--using the back button will disrupt the process!');
}

To implement this, add the following code at each stage of your program:

ignoreNextHashChange = true;
window.location.hash = '#hashForThisStage';

This method may not be foolproof, but it allows for controlled handling of back button actions without breaking the flow entirely.

Cheers!

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

Is there a way to halt the current traversal of visitEachChild in TypeScript Transformer API?

While navigating through each child node of a parent node using visitEachChild, is there a way to stop the process when I no longer wish to visit the subsequent child nodes? For example: Parent node Node 1 Node 2 <-- My target point. Node 3 Node 4 Nod ...

Retrieving the width and height of a DIV element using Javascript

Currently, I am attempting to retrieve the width and height of a div element as it is being changed by the user and then pass that data to another page. However, I am encountering difficulties in obtaining the width and height values. <script> $(fun ...

Angular: Backend responds with a token which Angular then stores within double quotes

Following the BE response, this code snippet is what I have: $cookieStore.put('Auth-Token', user.authToken); However, when checking the cookies, I notice that it displays Auth-Token: %220996dcbe-63e6-4d99-bd17-d258e0cc177e%22 Upon logging it to t ...

What is the best way to incorporate a Vue single file component into a Typescript-infused view?

Despite trying numerous methods, I consistently encounter build or runtime errors. To my surprise, I have not come across a functional example or post related to this inquiry after extensive research. I initiated a new project with Typescript using the Vue ...

Efficiently finding a group of substrings within a JavaScript string

I am currently working on a method to efficiently search for specific substrings within a given string. Here is my current implementation: const apple = "apple" const banana = "banana" const chickoo = "chickoo" const dates = & ...

Exploring the assortment of reactions post-awaitReaction in node.js

The current code runs smoothly, but I encounter an issue when attempting to send messages after selecting either the X or check option. Instead of the expected outcome, I receive Despite my understanding that this collection is a map, all attempts to acce ...

Calculating the total value of individual sections using Jquery

I have multiple sections, each containing three input fields: <div class="product_quantity"> <div class="color-quantity"> <input onkeydown="return myFunction(event);" name="custom_small" class="custom_small" type="text"> ...

Typescript in React is throwing an error that says you cannot destructure the property 'colored' from the 'boxShadows' object because it is undefined

After downloading the material dashboard react theme from an open source GitHub project, I tried to convert the project into Typescript (React + Typescript). However, I encountered the following error (See Attached Image) https://i.stack.imgur.com/YZKpK.p ...

What is the reason behind the inability to invoke a method when a class explicitly inherits from Object?

Issues arise when attempting to call an object method of a TypeScript class that explicitly extends Object: class Example extends Object { constructor() { super(); } public getHello() : string { return "Hello"; } } let gre ...

Struggling with Mocha, supertest, and passport when testing authenticated routes with JWT authentication

I've been experimenting with testing authenticated routes in Mocha, but I've run into an issue where the user created in the `before` or `beforeEach` hooks doesn't persist. Here's a snippet from my test.js: const should = require(&apo ...

Incorporate an SCSS file into the Stackblitz project

Is there a way to include an scss file in the stackblitz? I attempted it, but encountered some issues. Could you take a look and advise me on what to do? I also made an attempt to add home.html This is the project: Check out the stackblitz project here! ...

What is the best way to prevent the content within a div from being obscured by a sticky element affixed to the bottom of the div?

I am struggling with ensuring that the content in my wrapper does not get cut off by the "view more" div attached to the bottom. The default wrapper cuts off the children, and even when expanded, the issue persists due to CSS problems. In React, the gener ...

Is there a glitch in the console when sorting an array of dates?

I'm puzzled by the fact that the console is displaying a sorted array in both logs. It doesn't make sense to me because it should not be sorted at the first log, right? static reloadAndSortItems() { let array = []; const items = Store. ...

Synchronize data bidirectionally between parent and child components in Vue 2

This special wrapper I created for the Vue-multiselect package acts as a child component within this scenario. <template> <div> <multiselect v-model="items" :options="filteredList" ...

Steps to trigger a dialog to appear automatically within an Icon Menu with React Material UI

In my application, I have an icon menu implemented along with an array that contains the possible values for the items in the menu. Here is an example of how the array looks: listItems = { [ { label: 'ZERO', t ...

When attaching an event to two functions and then detaching it within a single function

When attaching an event to two functions and then removing it inside one function. Will both functions always be triggered by the event? Or is there a possibility that when the function with the unbind event is executed first, it will unbind both functio ...

The Vue conditional event handling with the v-on directive and the prevent modifier

Is there a way to utilize the .prevent modifier of v-on dynamically? <a href="#" class="modal-overlay" aria-label="Close" v-on="overlayClickClosesModal ? { click: () => closeModal() } : {}" /> I'm attempting to prevent the URL from ...

Looking to confirm client-side text in NodeJS?

As I work on constructing a to-do list, one challenge I am encountering is confirming that the correct task has been checked off. While considering using unique IDs for each individual task may seem like a solution, there is still the risk of users manipul ...

Issues with -moz-backface-visibility and tailwind css not being compatible

I'm currently facing an issue with the code in my tailwind.config.js file, specifically with the custom class for "moz-backface-visibility" that I've defined. tailwind.config.js /** @type {import('tailwindcss').Config} */ const plugin ...

Looking for a way to extract information from two nested objects within an array by utilizing lodash, and then transferring it as a property to a react component

My react components require dynamic preloading of values from nested arrays within an array of data. import React, { useEffect } from "react"; export function loadComponent({ config, LayoutRenderer }) { const loadModules = (name) => q ...