JS:尝试返回初始页面加载时出现错误的 popstate 事件

JS: Erroneous popstate event when trying to navigate back past the initial page load

我正在尝试使用 pushState/popState 实现 JS 历史记录。前后导航工作正常,但我在使用浏览器的后退按钮加载初始页面之前无法导航。它需要额外点击浏览器的后退按钮 1 次才能离开页面。这是为什么?

function action(text) {
  history.pushState({"text":text}, text);
  doAction(text);
}

function doAction(text) {
  $('span').text(text);
}

var $button = $('button');
var $p = $('p');

$p.hide();

action("foo");
$button.on('click', function(){
  action("bar");
  $button.hide();
  $p.show();
})

window.addEventListener("popstate", function(e) {
  if (e.state !== null) {
      $button.show();
      $p.text("Next back should navigate away from this page");
  } else {
      $p.text("Still here? Why is that? Next back will really navigate away");
  }
});

https://jsfiddle.net/lilalinux/p8ewyjr9/20/

编辑:使用 Chrome OS/X

测试

初始页面加载不应使用 history.pushState,因为它会 添加 另一个历史条目。已经有一个状态为 null.

的隐式第一个历史记录项

使用 history.replaceState 进行初始页面加载,设置该项目的状态但不添加另一个状态。

var initialPageLoad = true;
function action(text) {
  if (initialPageLoad) {
    // replace the state of the first (implicit) item
    history.replaceState({"text":text}, text);
  } else {
    // add new history item
    history.pushState({"text":text}, text);
  }
  initialPageLoad = false;
  doAction(text);
}

function doAction(text) {
  $('span').text(text);
}

var $button = $('button');
var $p = $('p');

$p.hide();

action("foo");
$button.on('click', function(){
  action("bar");
  $button.hide();
  $p.show();
})

window.addEventListener("popstate", function(e) {
  if (e.state !== null) {
      $button.show();
      $p.text("Next back should navigate away from this page");
//  } else {
// won't happen anymore, as the first item has state now
//      $p.text("Still here? Why is that? Next back will really navigate away");
  }
});