js 無刷新監聽URL的變化


無刷新改變路由的兩種方法


 

  • 通過hash改變路由

代碼:

window.location.hash='edit'

效果:

http://xxxx/#edit
  • 通過history改變路由
history.back(): 返回瀏覽器會話歷史中的上一頁,跟瀏覽器的回退按鈕功能相同
history.forward():指向瀏覽器會話歷史中的下一頁,跟瀏覽器的前進按鈕相同

history.go(): 可以跳轉到瀏覽器會話歷史中的指定的某一個記錄頁

history.pushState()可以將給定的數據壓入到瀏覽器會話歷史棧中,該方法接收3個參數,對象,title和一串url。pushState后會改變當前頁面url

history.replaceState()將當前的會話頁面的url替換成指定的數據,replaceState后也會改變當前頁面的url

  

監聽url變化


 

  • 監聽hash變化

通過hash改變了url,會觸發hashchange事件,只要監聽hashchange事件,就能捕獲到通過hash改變url的行為。

window.onhashchange=function(event){
  console.log(event);
}
//或者
window.addEventListener('hashchange',function(event){
   console.log(event);
})
  • 監聽back/forward/go

如果是history.back(),history.forward()、history.go()那么會觸發popstate事件

window.addEventListener('popstate', function(event) {
     console.log(event);
})

但是,history.pushState()和history.replaceState()不會觸發popstate事件,所以需要自己手動增加事件

  • 監聽pushState/replaceState

history.replaceState和pushState不會觸發popstate事件,那么如何監聽這兩個行為呢。可以通過在方法里面主動的去觸發popstate事件。另一種就是在方法中創建一個新的全局事件。

  • 改造
const _historyWrap = function(type) {
  const orig = history[type];
  const e = new Event(type);
  return function() {
    const rv = orig.apply(this, arguments);
    e.arguments = arguments;
    window.dispatchEvent(e);
    return rv;
  };
};
history.pushState = _historyWrap('pushState');
history.replaceState = _historyWrap('replaceState');

  

  • 監聽
window.addEventListener('pushState', function(e) {
  console.log('change pushState');
});
window.addEventListener('replaceState', function(e) {
  console.log('change replaceState');
});

  

轉自:https://segmentfault.com/a/1190000022822185


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM