历史记录推送状态后前进按钮无法工作

13

我已经找到了如何修复后退按钮,但前进按钮仍然无法修复。URL将会改变但页面不会重新加载,这是我正在使用的方法:

$('.anchor .wrapper').css({
  'position': 'relative'
});

$('.slanted').css({
  'top': 0
});

// Do something after 1 second
$('.original-page').html('');
var href = '/mission.html'

console.log(href);
// $('#content-div').html('');

$('#content-div').load(href + ' #content-div');
$('html').scrollTop(0);
// loads content into a div with the ID content_div

// HISTORY.PUSHSTATE
history.pushState('', 'New URL: ' + href, href);
window.onpopstate = function(event) {
  location.reload();
};

//            response.headers['Vary'] = 'Accept';
//            window.onpopstate = function (event) {
//                alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
//                            location.reload();
//                        response.headers['Vary'] = 'Accept';
//            };

//            $(window).bind('popstate', function () {

//            window.onpopstate = function (event) {
//                window.location.href = window.location.href;
//                location.reload();
//            };

e.preventDefault();

你可以看到,我尝试了几种不同的方法,后退按钮可以正常工作,但是前进按钮无法操作。

3个回答

26

请记住,history.pushState()将新状态设置为最新的历史状态。当您在已设置的状态之间向前/向后导航时,将调用window.onpopstate

因此,在调用window.onpopstate时不要pushState,因为这将把新状态设置为最后状态,然后无法向前导航。


5
这正是我所需要的。在阅读这个答案之前,我没有意识到我正在这样做。我必须把history.pushState的调用从函数中分离出来,这样当我使用window.onpopstate时就不会调用history.pushState了。 - Timothy Fisher
1
好的,这个完美地运行了。节省了我很多时间。 - ANAND SONI

2

通过多次点击后退和前进导航来完善解决方案。

全局注册window.onpopstate事件处理程序,因为在页面重新加载时会重置此处理程序(然后第二次和多次导航点击将无法正常工作):

window.onpopstate = function() {
    location.reload();
};

此外,更新函数执行AJAX重新加载(对于我的用例替换查询参数):

function update() {
    var currentURL = window.location.href;
    var startURL = currentURL.split("?")[0];

    var formParams = form.serialize();

    var newURL = startURL + "?" + formParams;
    var ajaxURL = startURL + "?ajax-update=1&" + formParams;

    $.ajax({
        url: ajaxURL,
        data: {id: $(this).attr('id')},
        type: 'GET',
        success: function (dataRaw) {
            var data = $(dataRaw);

            // replace specific content(s) ....

            window.history.pushState({path:newURL},'',newURL);
        }
    });
}

0
我建议阅读关于浏览器历史导航和pushState()方法的相关内容这里。它明确指出,pushState()本身不会导致浏览器加载页面。
至于前进按钮无法工作的问题,一旦调用了pushState(),浏览器(在概念上)处于历史记录的最后(最新)页面,因此没有更多页面可以“前进”到。

5
我理解您的意思是,使用pushState后点击浏览器的“后退”按钮后,再尝试使用“前进”按钮会发生什么。 - dan178

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接