2016-05-17 193 views
5

这里的pushStatepopstate事件的一个简单的例子:如何在触发popstate事件时获取上一页的URL?

<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事件时,你得到以前页面的网址是什么?


P.S.我试过document.referrer但它没有显示任何东西。

回答

0

请尝试将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> 
0

带有PopStateEvent。我用

window.history.pushState({} , {} , url); 

其他方式我不确定。

下面我测试了它的工作。我希望有所帮助。

window.addEventListener('popstate', function(e){ 
    console.log(e.srcElement.location); 
    /* You get other location types( 'http://....' or '/index.html' */ 
    var previusUrl = e.srcElement.location.href; 
    console.log(previusUrl); 
    // with http://............ 
}); 
相关问题