This solution demonstrates how to control and prevent back navigation in a browser when dealing with iframes. By using the history.pushState method and overriding the onpopstate event, this technique ensures that users can’t navigate back to previous pages in both the parent window and iframe.
example:
history.pushState(null, ‘’, window.location.href);
window.onpopstate = function () {
history.go(1); // Prevent back navigation in the current window
};
if (bh.system.environment.properties.MOTOR_CLAIMS_DCP == ‘true’) {
// Inside the iframe
parent.history.pushState(null, ‘’, parent.location.href);
parent.onpopstate = function () {
parent.history.go(1); // Prevent back navigation in the parent window by moving forward
};
}
Explanation:
- history.pushState: Adds a new state to the browser history without changing the URL.
- window.onpopstate: Intercepts the back button and prevents the browser from navigating back by calling
history.go(1). - For the Iframe: The code ensures that even if the iframe tries to trigger a back navigation, it will be handled by modifying the parent window’s history, effectively preventing any backward navigation.
This method is useful for scenarios like single-page applications (SPAs) or applications within iframes where you want to prevent users from navigating back and breaking the flow of the app.