Assigning to document.location.href without clobbering history
Solution 1
I was facing the same problem and found this workaround which worked for me
instead of
function onAjaxCallback(evt){
location.href=newLocation;
}
i wrapped the location.href call around a setTimeout. Seems to do the trick. My history's behaving fine now. Hope that helps
function onAjaxCallback(evt){
setTimeout(function(){
location.href=newLocation;
},0)
}
Solution 2
You could change the location without having the browser display a Back button like this:
window.location.replace(new_url);
However, the original address remains in the browser's history and may be accessed using something like CTRL+H
Reference:
- https://developer.mozilla.org/en/DOM/window.location#replace
- https://developer.mozilla.org/En/DOM/Window.history#Notes
Solution 3
study: window.location.replace()
and window.location.assign()
Solution 4
URL can be manually added to history before redirecting the user.
if (window.history) {
history.pushState({}, window.location.href);
}
window.location.replace("/login/?next=" + window.location.pathname);
Solution 5
Read the original question more carefully. The question is not about content loaded by an XHR, but about content loaded by a script loaded by an XHR. I had the same problem and the setTimeout method seems to work well.
Related videos on Youtube
wolffiex
Updated on November 26, 2020Comments
-
wolffiex over 3 years
In testing document.location.href, I have observed that when the user initiates an action that results in javascript that assigns to document.location.href, the new URL is added to the history.
However, if the call is initiated by javascript that is result of, say, state change of an XMLHTTPRequest, the entry for the current page in the history is over-written. Have I characterized this correctly? Is there a way to get the page change to be reflected in the history in this latter case?
-
royston over 14 yearsbtw tested on chrome, ff3.5 and ie8
-
pavsaund over 14 years+1 this solved my problem over at stackoverflow.com/questions/1629285/…
-
vladimir83 over 5 years
window.location.replace
replaces the current history item so you can't go back to it.pushState
is not needed ifwindow.location=...
is used.