Clear html history created by pushState on refresh
Asked Answered
H

4

15

I have array of states and index of the array in history.state and on popstate I read the content of the array, it work fine but when I go back to first page and refresh the array is gone (which is normal) but forward history state remain.

Is it possilbe to remove fake history that was created using pushState?

I can't store my state in localStorage because I have functions in my state array.

Honig answered 9/4, 2014 at 20:42 Comment(1)
You could set a new state using pushState or replaceState on pageload, it will remove the forward history.Unionism
D
17

If you read the specification of History API for pushState, in step 4 it states

  1. If the method invoked was the pushState() method:
    Remove all the entries in the browsing context's session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

So depending on what you are trying to do, you could make a special case for when first loading the page and push a state (one you will consider your first), and in doing so clear the forward states of the history.

Dilatometer answered 21/5, 2014 at 12:16 Comment(2)
Almost work, but when I create pushState onInit (refresh) I've got two pages in history, original real page and fake one from pushState. replaceState also don't work because it don't clear the history only change current one. It's not perfect, but probably you can't do any better.Honig
Needs a reference update.Glialentn
S
5

There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace() method, which replaces the current item of the session history with the provided URL. Mozilla

The only way is this (but I think you know it)

var length=history.length;     
history.go(-length);
window.location.replace("urlToRedirect");

after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Schottische answered 21/5, 2014 at 12:32 Comment(1)
However, the user can go forward, because replace will not remove history ahead.Bs
L
5

My idea - override whole history:

for (i = 0; i < 50; i++) {
  history.pushState({}, '');
}
Legation answered 5/8, 2016 at 13:13 Comment(2)
For what it's worth, my virus scan prevented this due to "history injection", so it might not work on all clients.Thalassography
This just fills the history with entries of the current page.Wilkens
B
-1
window.history.replaceState('page', '');

this code on page load will prevent a double back button

Bison answered 16/1, 2020 at 14:45 Comment(1)
This don't answer the question, this just replace last url. not clear history. Read first and only comment.Honig

© 2022 - 2024 — McMap. All rights reserved.