当触发popstate事件时,我该如何获取上一页的URL?

20

这是一个简单的 pushStatepopstate 事件示例:

<button id="example_btn">Click me</button>

<script>
$("#example_btn").click(function(){
            history.pushState( 
                {
                    'url' : "example.htm"
                }, null, "example.htm");
});
$(window).bind('popstate', function (event) {
    if (event.originalEvent.state) {
        console.log(event.originalEvent.state.url);
    }
});
</script>

当触发popstate事件时,它会显示当前页面的URL。

我的问题是:

在这种情况下,如何在触发popstate事件时获取前一个页面的URL?


P.S. 我尝试过document.referrer但它没有显示任何内容。

2个回答

4
请尝试将previousUrl保存在一个变量中并监听它。
<button id="example_btn">Click me</button>

<script>
var previousUrl = null;
$("#example_btn").on('click', function(){
           previousUrl = location.href;
             history.pushState( 
                {
                    'url' : "example.htm"
                }, null, "example.htm");
});
window.onpopstate = function (event) {
   console.log('Previous url was : ', previousUrl); 
};
</script>

2
如果用户在层次结构中向后导航多个状态,该怎么办? - Marian Klühspies

0

已更新、测试并且可用


扩展历史对象

这是我的源代码,你可以从https://gist.github.com/HasanDelibas/12050fc59d675181ea973d21f882081a查看完整资源。


这个库包含以下内容:

  • history.states -> 获取状态列表
  • history.stateIndex -> 当前状态索引
  • "historyChange" 事件 -> 检测历史记录更改(从,到,方向="back"|"forward")
  • 重要! state 必须是对象在history.pushState( **state**, ...)
(function(){
  let stateSymbol = "__state__index__";
  history.stateIndex =-1;
  history.states=[];
  let pushState = history.pushState;
  function add(data,title,url){
    if(data==null) data={};
    if(typeof data!="object") data={data:data};
    data[stateSymbol] = (history.stateIndex+1);
    history.states.splice(history.stateIndex+1,0,[data,title,url])
    history.states.splice(history.stateIndex+2)
    history.stateIndex++;
  }
  history.pushState =function(data,title,url=null){
    add(data,title,url);
    pushState.bind(history)(data,title,url);
  }
  addEventListener("popstate",function(e){
    var eventObject= {};
    var newStateIndex =  e.state!=null ? e.state[stateSymbol] : -1;
    eventObject.from = history.states[history.stateIndex];
    eventObject.to   = newStateIndex>-1 ? history.states[newStateIndex] : null;
    eventObject.side = history.stateIndex>newStateIndex ? "back" : "forward"; 
    if( newStateIndex > -1 && !(newStateIndex in history.states) ){
      add(history.state,"",window.location.href);
    }
    window.dispatchEvent(new CustomEvent("historyChange", {detail: eventObject} ))
    history.stateIndex = e.state!=null ? e.state[stateSymbol] : -1;
  });
})();

现在您可以使用history.states对象获取所有状态, 并通过addEventListener(“popstate”,function(e))检测历史更改。

使用

/**
  * @param e.detail.from [data,title,url]
  * @param e.detail.to   [data,title,url]
  * @param e.detail.side "back" | "forward"
  */
addEventListener("historyChange",function(e){
  var from = e.detail.from; // [ data , title , url ]
  var to   = e.detail.to;   // [ data , title , url ]
  var side = e.detail.side; // "back" | "forward"
  console.log( `You changed history. Side is ${e.detail.side}.\nFrom:${e.detail.from[2]}\nTo:${e.detail.to[2]}`)
})


history.pushState("1", "DENEME-TEST" ,"?1");
history.pushState("2", "DENEME-TEST" ,"?2");
// list of history states
console.log( history.states )
/*
[
  [ {...} ,  "DENEME-TEST" ,"?1" ]
  [ {...} ,  "DENEME-TEST" ,"?2" ]
]
*/
// get history current state index
console.log( history.stateIndex )
/*
1
*/


1
这显示当前的URL,但不是popstate之前的URL。 - Björn Tantau
这里的好主意是扩展历史对象,以便能够探索所有的后退和前进状态。旧的URL只是先前状态的URL。 - Gunther Schadow

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