繁体   English   中英

前进按钮在 history.pushState 后不起作用

[英]Forward button not working after history.pushState

我已经找到了如何修复后退按钮,但前进按钮仍然无法修复。 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();

如您所见,我尝试了几种不同的方法,后退按钮工作正常,但前进按钮无效。

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

所以当window.onpopstate被调用时不要pushState ,因为这会将新状态设置为最后一个状态,然后就没有什么可前进的了。

多次单击后退和前进导航的完整解决方案。

全局注册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);
        }
    });
}

我建议在此处阅读有关浏览浏览器历史记录和pushState()方法的内容。 它明确指出pushState()本身不会导致浏览器加载页面。

至于前进按钮不起作用,一旦您调用pushState()浏览器(概念上)位于历史记录的最后(最新)页面,因此没有进一步的页面可以“前进”到。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM