How to remove hash (anchor) from browser history before load another page (follow link)

Viewed 234

I have a menu (sidebar) for small screens devices, when user open the menu, it run:

window.history.pushState(null, null, "#menu");

Once I want that it closes when user click in back button (android devices) which is possible with the code bellow:

$(window).on("popstate", closeMenu)

So if user click in back button, it back to previous state (remove #menu from url and run the function closeMenu).

everything works as expected, but if user navigate through pages by menu's links as the example bellow:

  • user is in home;
  • go to page x;
  • go to page y,
  • and back to page x.

now is needed to press back button twice to go home

It is happening because window.history.pushState is adding a new history to browser. The menu is opened when user click in any link, so the current url when request is: mysite.com/anyPage#menu;

The browser navigates from mysite.com/anyPage#menu to mysite.com/anotherPage.

every time the user back to page X, and go to another, then back to X again, it add to the history one more (#).

I was able to reduce the amount of # in history by:

//(instead the first code)
    if (!(window.location.toString().indexOf("#") > 0)) {
        window.history.pushState(null, null, "#menu");
    }

So the max unwanted page in history now is 1 (what makes user click twice in button); What is the best way to fix it? I think if run window.history.back() before load next page may works, but I had no success to do it.

I thought about use window.onbeforeunload, then in my function:

window.history.back()

but it stop the navigation to next link and makes the browser back one page instead follow the link I also thought about replaceState:

  let uri = window.location.toString();
  if(uri.indexOf("#")>0){
      uri = uri.substring(0,
      uri.indexOf("#"));
  }
                  
  history.replaceState(null, '', uri);
                

I can see in URL browser removing the #menu from URL but I think at this point browser already requested the link page from the source url containing #. Or am I wrong?

Once I was not able to get the element which makes browser to load like:

//onbeforeunload:
e.target.activeElement
document.activeElement

I thought also instead use onbeforeunload, handle click event in all links in menu, so I could to run window.history.back() before request the new page and programmatically open the link, but I don't know if its the best approach

0 Answers
Related