Skip to content
Advertisement

window.history.pushState refreshing the browser

I am working on some javascript code, and using window.History.pushState to load new HTML pages, instead of using href tags. My code (which is working fine) looks like this.

window.History.pushState({urlPath:'/page1'},"",'/page1')

strangely, this fails, ie reloads the browser

window.History.pushState({urlPath:'/page2.php'},"",'/page2.php')

But this works, content is updated, browser not refreshed ! (notice the URL is absolute and not relative)

window.History.pushState({urlPath:'www.domain.com/page2.php'},"",'www.domain.com/page2.php')

The documentation for window.History.pushState says that the third parameter URL can be either absolute or relative –

URL — The new history entry’s URL is given by this parameter. Note that the browser won’t attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it’s relative, it’s resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn’t specified, it’s set to the document’s current URL.

Absolute URLs seem to be working but relative seem to be not. Why is this happening?

Advertisement

Answer

The short answer is that history.pushState (not History.pushState, which would throw an exception, the window part is optional) will never do what you suggest.

If pages are refreshing, then it is caused by other things that you are doing (for example, you might have code running that goes to a new location in the case of the address bar changing).

history.pushState({urlPath:'/page2.php'},"",'/page2.php') works exactly like it is supposed to in the latest versions of Chrome, IE and Firefox for me and my colleagues.

In fact you can put whatever you like into the function: history.pushState({}, '', 'So long and thanks for all the fish.not a real file').

If you post some more code (with special attention for code nearby the history.pushState and anywhere document.location is used), then we’ll be more than happy to help you figure out where exactly this issue is coming from.

If you post more code, I’ll update this answer (I have your question favourited) :).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement