Assigning to [removed].href without clobbering history

前端 未结 6 1223
渐次进展
渐次进展 2020-12-01 19:04

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 a

相关标签:
6条回答
  • 2020-12-01 19:30

    Alas, your question can't be answered, AJAX requests have nothing to do with browser history, and if you loaded some dynamic content with them, then the user clicked the browser back button, the previous page is loaded (this which was loaded with an ordinary GET or POST request), which corrupts the sequence you display content in.

    Dmitri's answers means that you will maintain your own history for the dynamic content using the fragment part of the url (this after the # symbol), maybe you'll provide your own back and forward buttons, but still you're not protected from the effect of the browser back and forward buttons.

    If only they had provided some kind of events to handle user clicks on these buttons with the ability to cancel.

    0 讨论(0)
  • 2020-12-01 19:38

    study: window.location.replace() and window.location.assign()

    0 讨论(0)
  • 2020-12-01 19:44

    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
    0 讨论(0)
  • 2020-12-01 19:44

    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.

    0 讨论(0)
  • 2020-12-01 19:44

    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);
    
    0 讨论(0)
  • 2020-12-01 19:51

    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)
    }
    
    0 讨论(0)
提交回复
热议问题