Search code examples
javascriptangularbrowser-history

Is there a way to close a modal using Back button without tampering browser history states?


I have a rather specific use case.

Imagine I navigate from Page A to Page B (adds one history state). On Page B then I interact with the page by opening a modal. But the modal is implemented in a way that it closes when browser back button is clicked.

when modal is opened:

ngOnInit(): void {
        history.pushState(null, null, this.pageBHomeUrl + "?modal");
    }

and when it's closed the modal state is replaced with the previous home url:

close(): void {
        history.replaceState(null, null, this.pageBHomeUrl);
    }

When I close the modal, my browser history looks like this (most recent first)

  • pageBHomeUrl
  • pageA

However, I want to make sure that I can close the modal while keeping Page A as the most recent history state... Is there a way to delete pageBHomeUrl history state or move pageA state forward? Or close a modal using a back button without changing history states?


Solution

  • When you navigate from A to B, your history looks like this:

    • pageA
    • pageBHomeUrl - current

    When you open the modal and call pushState, your history will look like this:

    • pageA
    • pageBHomeUrl
    • pageBHomeUrl?modal - current

    When you then close the modal using the button and call replaceState, your history will look like this:

    • pageA
    • pageBHomeUrl
    • pageBHomeUrl - current

    This is not what you want. Instead of replaceState, use popState in the close handler to get back from the modal to the desired history:

    • pageA
    • pageBHomeUrl - current