Skip to content

Improve router work with history.state #28954

Closed

Description

@samogot

🚀 feature request

Relevant Package

This feature request is for @angular/router

Disclaimer

This feature request can be broken down to several separate issues (bugs and FRs) but I've decided to create one issue to describe my actual use case, problems I have encountered, ideal solution I'd like to have and workaround I came up with.

Use case

I'm working on web site for reading books. I have some "reader" page with infinite scroll that loads next chapter when user scrolls near to of a page. When some chapter enters view-port, I change browser URL to this chapter without triggering navigation (using Location.replaceState).

If users scroll to some next chapter and then reload page or go back/forward in history, they lost scroll position, because saved scroll position (on page with several chapters) is greater then reloaded page length (on page with only "last" chapter)

The idea was to use history.state to save scroll position relative to current chapter top.

Problems

Saving position was pretty straightforward, because Location.replaceState method already has state property. But restoring this state is a pain.

Thanks to #27198 router already knows something about history state, current design/implementation isn't enough do described use case. I didn't figure out why we need both NavigationStart.restoredState and NavigationExtras.state, but despite similar description, they are not the same.

Router itself lacks public method that behaves like Location.replaceState (#24617), and any "outside" changes to history.state are not available as NavigationExtras.state of Router.getCurrentNavigation(), but only available as NavigationStart.restoredState. There is private setBrowserUrl method, that can be used for public implementation.

NavigationStart.restoredState of initial page load can't be reached inside component that is responsible for text rendering (i.e. in the place, which knows chapter top offset, where we need to add saved scroll position), because initial NavigationStart is fired before any component (except of AppComponent) is created. And there is no way to get this value otherwise, except of catching it in AppComponent and saving in some service.

Buy the way workaround from #27198 (comment) to pass NavigationStart.restoredState as NavigationExtras.state doesn't work (any more?) because of resetting currentNavigation here in case of "redirect during NavigationStart".

And even if we can get NavigationStart.restoredState in such hackish way, there is no sense to do this, because of bug. We don't get load any stored state from history in initial navigation (see null in line 951 called from line 778)

Actually we don't even have a way to get this initial state, because all classes on the way from Location, through LocationStrategy, PathLocationStrategy, PlatformLocation, BrowserPlatformLocation up to History lacks an abstraction to get current state.

Hopefully we still can access window.history.state directly. But again, we cann't do it in the component code, because before we create component, router already resets saves history.state with {navigationId:1}. So I still need to write some hackish way to store this value somewhere before first ActivationStart event.

Describe the solution you'd like

I'd like to have a way to straightforwardly call something on router to replace current state and than be able to get this state in Scroll router event. I want this state to be persistently saved even after page reload to moving back/forward outside of angular application.

I don't really care how it will be implemented internally, but just fixing problems above should be enough.

Router should have it's own replaceState (or something) method, that encapsulate any logic around Location.replaceState to handle navigationId or any other possible future angular-specific internal structure of history.state (#27607) and also to provide state as NavigationExtras.state instead of NavigationStart.restoredState.

Describe alternatives you've considered

This section is mostly for someone looking for solution for exactly my use case.
Workaround I came up with consists of two parts.
First - I use resolver to get saved data directly from window.history.state.
Second - because of the same reason I can get data on initial page load - I receive wrong data on navigating away to another chapter. What do I mean? Consider following use case:

  • Initial page load without history.
  • No data in history -> no scrolling to position.
  • Scroll a bit, position is saved to history.
  • Reload page.
  • Router will rewrite history only on ActivationStart, so we get correct data in resolver.
  • There is data from resolver -> scroll to saved position.
  • Scroll a bit, position is saved to history.
  • Navigate to another chapter directly (there is contents feature in my app).
  • Router will rewrite history only on ActivationStart, so we get incorrect data of previous chapter in resolver.
  • There is data from resolver -> we scroll to incorrect saved position of previous chapter.

To workaround this problem, I save chapter id together with scroll position, so I can check is this data is relevant.
Final code looks something like this:

progress-resolver.service.ts:

import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from "@angular/common";
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from "@angular/router";

interface Progress {
  scroll: number,
  chapterId: number,
}

@Injectable({
  providedIn: 'root'
})
export class ProgressResolverService implements Resolve<Progress | null> {

  constructor(@Inject(PLATFORM_ID) private platformId: Object) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Progress | null {
    if (isPlatformBrowser(this.platformId) && window && window.history && window.history.state && window.history.state.progress) {
      return {
        scroll: window.history.state.scroll,
        chapterId: window.history.state.chapterId,
      };
    }
    return null;
  }
}

chapter-text.component.ts:

import { AfterViewInit, Component, ElementRef, Input, OnDestroy, ViewChild } from '@angular/core';
import { OnScrollService } from "../on-scroll/on-scroll.service";
import { ActivatedRoute } from "@angular/router";
import { Location, ViewportScroller } from "@angular/common";
import { debounceTime, filter, map } from "rxjs/operators";
import { Subscription } from "rxjs";

@Component({
  selector: 'app-chapter-text',
  templateUrl: './chapter-text.component.html',
  styleUrls: ['./chapter-text.component.scss']
})
export class ChapterTextComponent implements OnDestroy, AfterViewInit {
  @Input() chapter: any;
  private progressSub: Subscription;
  private subscription: Subscription;
  private position: { top: number; height: number };

  constructor(
    private elem: ElementRef,
    private route: ActivatedRoute,
    private onScroll: OnScrollService,
    private location: Location,
    private viewportScroller: ViewportScroller,
  ) {
  }

  ngAfterViewInit() {
    this.position = {
      top: this.elem.nativeElement.offsetTop,
      height: this.elem.nativeElement.offsetHeight
    };
    this.subscribe();
  }

  subscribe() {
    this.subscription = this.onScroll.scroll.pipe(
      filter(scroll => this.position.top < scroll && scroll < this.position.top + this.position.height),
      debounceTime(100),
    ).subscribe(scroll => this.location.replaceState(this.chapter.url, undefined, {
      ...window.history.state,
      scroll: scroll - this.position.top,
      chapterId: this.chapter.chapterId
    }));
    
    this.progressSub = this.route.data.pipe(
      map(data => data.progress),
      filter(progress => progress && this.chapter.chapterId == progress.chapterId),
      map(progress => progress.scroll),
    ).subscribe(scroll => this.viewportScroller.scrollToPosition([0, this.position.top + scroll]));
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
    this.progressSub.unsubscribe();
  }
}

Activity

  1. samogot commented on Feb 24, 2019

    @samogot
    Author

    @jasonaden, please take a look at this feature request. As far as I can see, you are the right person, who works with this area.

  2. added this to the needsTriage milestone on Feb 24, 2019
  3. colmben commented on Mar 28, 2019

    @colmben

    I am currently trying to implement a reasonable back button solution that would also allow some state manipulation in-page. The current way state and popstates are handled is very...peculiar!

    As this request says, the navigation process now has the ability to set state. Instead of just popping the stored state, location.back() actually creates a new navigation with a restoredState property in the NavigationStart event. Why?

    If you change the state with location.replaceState(), location.back wouldn't even find that state to restore, unless you also merge in the (correct? Not sure it needs to be the actual right number) navigationId. Why does it do this?

    What I was expecting to find when I saw these changes was an Angular implementation of the History API , which allows any arbitrary state to be placed in history and that state to be immediately available on a pop. Both Location and Router are using names that seem to be related to the History API (replaceState, back etc) but they aren't doing what you would expect from a History API compliant process. Why are we complicating the thing with navigation IDs and restored states? It feels like Location and Router are at cross purposes here and one or the other should properly implement the History API to allow intuitive state management over pops.

  4. jasonaden commented on Apr 4, 2019

    @jasonaden
    Contributor

    Thanks for the issue. I agree, we need much better APIs for dealing with history.state. I've got some ongoing work that might help with your use cases. But I wouldn't mind having a further discussion.

    If you can ping me on Twitter @jasonaden1 we could set up a time to discuss. I would like to see if what I'm currently implementing would end up working for your needs.

  5. added
    feature
    on Apr 4, 2019
  6. modified the milestones: needsTriage, Backlog on Apr 4, 2019
  7. samogot commented on Apr 8, 2019

    @samogot
    Author

    Sorry, I don't use twitter :)

  8. angular-robot commented on Jun 4, 2021

    @angular-robot
    Contributor

    Just a heads up that we kicked off a community voting process for your feature request. There are 20 days until the voting process ends.

    Find more details about Angular's feature request process in our documentation.

  9. colmben commented on Jun 4, 2021

    @colmben

    Just FYI for the 22 people who thumbs-up'ed the +1 comment, the angular voting process requires a thumbs-up on the first post, the one describing the feature request. This is currently sitting at 7 thumbs-up and requires 20 to be considered.

  10. added
    feature: under consideration
    on Jun 12, 2021
  11. anishmgoyal commented on Aug 10, 2021

    @anishmgoyal

    +1

    When reloading the page, state's lost. Going forward or back from the page after reload shows that OTHER pages retain their state, but the initially loaded page does not.

    After checking in the constructor for the app component, the value is definitely present - it's just that, for the first page, the router is ignoring it.

  12. cyraid commented on Aug 17, 2022

    @cyraid
    Contributor

    My use case is different, and it was kinda difficult to even find this github issue. There are probably others out there that face this issue and have to do workarounds. I use location.go() and try to store state without using navigate. I store the state, but when I listen for window:popstate event, the state just holds the navigationId, not the data I put into it. Is there not a way to get the state I put in, using a navigationId? Or better yet, don't erase my state data I put in? :)

  13. jksware commented on Aug 30, 2022

    @jksware

    For anyone with the same issue, I found a workaround that might suit you (although with a compromise, see at the end):

    1. On your router, set onSameUrlNavigation to reload.
    this.router.onSameUrlNavigation = 'reload';
    
    1. To save your current state, navigate to the same URL the browser is in, and include the state you want to save in the second argument.
    await this.router.navigateByUrl(this.router.url, { state: state });
    

    The compromise is that this method is effectively reprocessing the URL, as noted by the comments in the code for onSameUrlNavigation:

    Note that this only configures whether the Route reprocesses the URL and triggers related
    action and events like redirects, guards, and resolvers. By default, the router re-uses a
    component instance when it re-navigates to the same component type without visiting a different
    component first.

  14. robmv commented on Sep 15, 2022

    @robmv

    I wrote a workaround using a service. It listen for NavigationStart triggered by a popstate and store the native history.state before Angular touches it. Some top level component must inject it in order to not lose states before it is used down the component hierarchy.

    I hope this helps until Angular has better support for it.

    import { Location, PopStateEvent } from '@angular/common';
    import { Injectable } from '@angular/core';
    import { Event as REvent, NavigationEnd, NavigationError, NavigationStart, Router } from '@angular/router';
    import { filter, SubscriptionLike } from 'rxjs';
    
    @Injectable({
      providedIn: 'root',
    })
    export class NativeHistory {
      private isPopstate = false;
    
      private _state: unknown = window.history.state;
    
      constructor(
        private readonly router: Router,
        private readonly location: Location) {
        function filterPred(event: REvent): event is NavigationStart | NavigationEnd | NavigationError {
          return event instanceof NavigationStart || event instanceof NavigationEnd || event instanceof NavigationError;
        };
    
        this.router.events
          .pipe(
            filter(filterPred)
          )
          .subscribe(event => this.processEvent(event));
      }
    
      private processEvent(event: NavigationStart | NavigationEnd | NavigationError) {
        if (event instanceof NavigationStart) {
          if (event.navigationTrigger == 'popstate') {
            this.isPopstate = true;
            this._state = window.history.state;
          }
        } else if (event instanceof NavigationEnd) {
          if (this.isPopstate) {
            // The current state is stored again in order to not lose it after another navigation
            this.location.replaceState(this.location.path(), '', this._state);
            this.isPopstate = false;
          }
        } else {
          this.isPopstate = false;
          this._state = undefined;
        }
      }
    
      get state(): unknown {
        return this._state;
      }
    }
  15. nebkat commented on Nov 10, 2022

    @nebkat
    Contributor

    I think a lot of this thread has lost focus from the core problem:

    Goal

    The goal is to allow the current state to be modified after a page has been loaded, i.e. to reflect user interactions. This is essential to maintain intuitive forward/back navigation. History.replaceState() provides a way to achieve this natively.

    Issue

    The issue is that the Angular Router uses history.state for it's own internal functionality and unintentionally interferes with history.state after popstate events (forward/back events).

    Since #27198 the router allows a state to be passed when navigating, but there is no clean way for the app to modify the state on the current page after navigation. As originally suggested by @samogot, there should be a Router.replaceState() method to mirror History.replaceState() without URL changes.

    There is also a bug that causes the router to discard the state if the internal fields added by the router are not present when forward/back navigation occurs. This means that if the user manually calls History.replaceState(), the state will later be overwritten when returning to the page.

    This bug is not a regression but rather the router was never built to handle app states and it is an unintended consequence of some very old code.

    Workaround

    There is currently a very simple workaround that appears to fix the problem entirely, but it is really just a hack to patch the bug in the router.

    history.replaceState({ ...history.state, foo: 'bar' }, '')
    // OR
    history.replaceState({ navigationId: history.state.navigationId, foo: 'bar' }, '')

    Solution


    I have done far too much digging to discard this post, hopefully it will help in making future decisions.

    Short History

    2016

    • The router originally did not care about history states at all, and their use by the app was undocumented.
    • Whenever history.pushState() was used by the router, null was always provided as the state.
    • However, there was logic to avoid resetting states after forward/back navigation.

    2016

    • eb2ceff (unintentionally?) removes this logic and causes state to be reset on every popstate
    • Arguably the beginning of the bug, state is always overwritten.

    2018

    • af2c0b3 starts using history.state to store navigationId and then populates NavigationStart.restoredState with it.
    • Motives are unclear, restoredState seems completely unnecessary at this point?
    • Bug behavior isn't changed, but logic to extract navigationId from state is introduced which later gets misinterpreted.

    2019

    • Allow setting history.state when navigating #27198 allows state to be passed with Router.navigate()
    • f7ef94a rewrites earlier navigationId extract logic to also include the entire state object, but still only if navigationId is present.
    • The documentation makes it explicit that this value is stored in history.state, and popular StackOverflow questions confirm the same.
    • Bug behavior isn't changed, still on every popstate the state is reset - only the restoredState is somewhat handled.

    2020

    • df76a20 partially fixes the bug and attempts to restore the state correctly, but still relies on navigationId being present.

    Long History

    We start with eb2ceff way back in 2016.

    The router uses history.pushState() and history.replaceState() to change the URL displayed in the browser without refreshing the page. null is always passed as the state parameter, as the router does not still make any use of the state.

    When the browser forward/back buttons are pressed (or location.forward()/location.back()) are used, a popstate event is emitted. The router listens for this in order to handle the necessary routing changes.

    Previously, when the router detected a popstate event, skipLocationChange would be used to avoid further altering the state with history.replaceState() within the router, as there was no need for this.

    In order to solve #13491, skipLocationChange is disabled for popstate/hashchange event routing. I am not sure if this was the intended result of the commit, but from this point on it seems any popstate even will cause state to be set to null due to the forced location reset.


    Next there is af2c0b3 in 2018.

    This commit adds navigationTrigger and restoredState to the NavigationStart event. navigationTrigger is a useful addition to allow differentiating between imperative and popstate changes. However, restoredState seems entirely redundant:

    /**
    * Identifies the trigger of the navigation.
    *
    * * 'imperative'--triggered by `router.navigateByUrl` or `router.navigate`.
    * * 'popstate'--triggered by a popstate event
    * * 'hashchange'--triggered by a hashchange event
    */
    navigationTrigger?: 'imperative'|'popstate'|'hashchange';

    /**
    * This contains the navigation id that pushed the history record that the router navigates
    * back to. This is not null only when the navigation is triggered by a popstate event.
    *
    * The router assigns a navigationId to every router transition/navigation. Even when the user
    * clicks on the back button in the browser, a new navigation id will be created. So from
    * the perspective of the router, the router never "goes back". By using the `restoredState`
    * and its navigationId, you can implement behavior that differentiates between creating new
    * states
    * and popstate events. In the latter case you can restore some remembered state (e.g., scroll
    * position).
    */
    restoredState?: {navigationId: number}|null;

    navigationId is an internal field used by the router and to my knowledge is not meaningful outside of the router. The comment suggests that checking for its presence would indicate if a popstate triggered the navigation, but why do this when it is already evident from navigationTrigger?

    In this commit it appears the addition of navigationId to state was solely for the purposes of populating restoredState, which as per the above should be unnecessary, so I am totally confused as to why it was done. #27607 seems to discuss this.

    The popstate handling code is made to handle the requirements of restoredState - which complicates things later:

    this.locationSubscription = <any>this.location.subscribe(Zone.current.wrap((change: any) => {
    const rawUrlTree = this.urlSerializer.parse(change['url']);
    const source: NavigationTrigger = change['type'] === 'popstate' ? 'popstate' : 'hashchange';
    const state = change.state && change.state.navigationId ?
    {navigationId: change.state.navigationId} :
    null;
    setTimeout(
    () => { this.scheduleNavigation(rawUrlTree, source, state, {replaceUrl: true}); }, 0);
    }));

    Line 315 just extracts the navigationId from the state and creates a new object. Whether it is present will solely depend on whether the popped state was originally navigated to by the router or manually by the app with a pushState or replaceState, and not in line with what the documentation described for restoredState above.


    Later on #27198 introduces the ability to pass a state during navigation, and it appends the navigationId field as before.

    A commit from the PR, f7ef94a deals with the popstate state handling code slightly differently:

    // Navigations coming from Angular router have a navigationId state property. When this
    // exists, restore the state.
    const state = change.state && change.state.navigationId ? change.state : null;

    The purpose here is probably to maintain the behavior of restoredState being null if navigationId is not present - but now that restoredState contains the entire state it is even more unclear why we would want to do this.

    At this time, the state is still being force reset after every popstate.


    Finally in df76a20, a partial fix is made to allow the state to be maintained using the extras.state parameter.

    It continues to discard the state unless navigationId is present.

  16. atscott commented on Nov 11, 2022

    @atscott
    Contributor

    @nebkat Appreciate the detailed research here. I don't have the full history either, but I've discovered information that I believe to be true after inheriting ownership of the Router code around 2019:

    Remove unnecessary and confusing restoredState field. #27607 closed as completed?

    This was probably closed before GitHub's feature that allowed you to close as won't do vs completed. It was closed as “not worth it”. The unfortunate truth is that it is public API and applications do use it (though it’s rare). Removing it would be a pretty big headache.

    navigationId is an internal field used by the router and to my knowledge is not meaningful outside of the router.

    The navigationId on the history state is used in two places:

    1. The router scroller to restore the stored scroll position for that item in history (this is actually mentioned in the docs.
    2. The upgrade code to coordinate AngularJS/Angular hybrid apps.

    • Add a Router.replaceState() method that allows the app to alter the state on a page without affecting router internal operation. TODO

    The solution for this is certainly up for debate. I don’t know if adding a replaceState is necessary. We will be adding an onSameUrlNavigation option to the navigate method to override the default (which is ignore). So you could instead do router.navigate([], {state: newState, onSameUrlNavigation: ‘reload’});

  17. atscott commented on Dec 3, 2023

    @atscott
    Contributor

    Closing as generally not relevant anymore. @nebkat outlined quite a few changes that improved things since this was reported and contributed #48033 to shore up yet another issue. There are a lot of options now, including the availability of onSameUrlNavigation in the navigation extras to effectively reload a route with new state.

    If there are still specific issue that need to be addressed, please open a new issue and follow the instructions in the issue template that include info on how to create a reproduction using our template.

  18. deleted a comment from TerrorLumpiRaf on Dec 3, 2023
  19. angular-automatic-lock-bot commented on Jan 3, 2024

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  20. locked and limited conversation to collaborators on Jan 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: routerfeaturefeature: under considerationfreq3: high

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions