【问题标题】:JS: Erroneous popstate event when trying to navigate back past the initial page loadJS:尝试导航回初始页面加载时出现错误的 popstate 事件
【发布时间】:2018-09-26 11:31:45
【问题描述】:

我正在尝试使用 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 测试

【问题讨论】:

    标签: javascript browser-history


    【解决方案1】:

    初始页面加载不应使用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");
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 2011-09-19
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 2019-07-25
      相关资源
      最近更新 更多