Failed to execute 'pushState' on 'History' error when using window.history.pushState function
Asked Answered
E

3

39

I'm using window.history in JavascriptMVC application to enable back/forward/refresh functionality for each controller. Every time I load a new controller I'm using window.history.pushState to add a new state to history. And then on back/refresh I'm using the saved state and reuse the data to build the controller again.

The whole idea works fine excepting one issue on specific scenario. I'm getting the following error:

Failed to execute 'pushState' on 'History': An object could not be cloned.

The same data is added without problem on other scenario. What can cause this error? Thanks for the assistance.

Eunuchize answered 26/6, 2014 at 8:33 Comment(0)
G
68

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

"The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage."

Looks like the simple answer is that possible the state you are passing in is serializing to larger than 640k. I just ran into this bug, and I am almost certain that is the cause.

Gnarl answered 10/10, 2014 at 3:41 Comment(3)
Thanks for the response. The problem was caused by some cyclic dependencies in objects that I was trying to save and serialize. After I removed the cyclic dependencies it was resolved.Eunuchize
I had the same problem because I was passing a DOM element to the state object. Not a good idea. Thanks for the answer: really helpful.Mathias
Got same error using Knockout because I was not dereferencing the observable - trying to push ID when I should have been pushing ID()Fragmental
G
9

window.history.pushState string size limit of 640k characters.

Better switch to localStorage or sessionStorage.

Source: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

Gerstein answered 8/3, 2020 at 10:3 Comment(0)
V
1

Try to pass the object in a queryParams:

this.router.navigate(['yourRoute'], { queryParams: objectToPass});

That works for me.

Variole answered 13/2, 2022 at 1:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.