js實現(xiàn)無刷新監(jiān)聽URL的變化示例代碼詳解
無刷新改變路由的兩種方法通過hash改變路由
代碼
window.location.hash='edit'
效果
通過history改變路由
- history.back(): 返回瀏覽器會話歷史中的上一頁,跟瀏覽器的回退按鈕功能相同
- history.forward():指向瀏覽器會話歷史中的下一頁,跟瀏覽器的前進按鈕相同
- history.go(): 可以跳轉(zhuǎn)到瀏覽器會話歷史中的指定的某一個記錄頁
- history.pushState()可以將給定的數(shù)據(jù)壓入到瀏覽器會話歷史棧中,該方法接收3個參數(shù),對象,title和一串url。pushState后會改變當前頁面url
- history.replaceState()將當前的會話頁面的url替換成指定的數(shù)據(jù),replaceState后也會改變當前頁面的url
監(jiān)聽url變化
監(jiān)聽hash變化
window.onhashchange=function(event){ console.log(event); } //或者 window.addEventListener('hashchange',function(event){ console.log(event); })
監(jiān)聽back/forward/go
如果是history.back(),history.forward()、history.go()那么會觸發(fā)popstate事件
window.addEventListener('popstate', function(event) { console.log(event); })
但是,history.pushState()和history.replaceState()不會觸發(fā)popstate事件,所以需要自己手動增加事件
監(jiān)聽pushState/replaceState
history.replaceState和pushState不會觸發(fā)popstate事件,那么如何監(jiān)聽這兩個行為呢??梢酝ㄟ^在方法里面主動的去觸發(fā)popstate事件。另一種就是在方法中創(chuàng)建一個新的全局事件。
改造
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');
監(jiān)聽
window.addEventListener('pushState', function(e) { console.log('change pushState'); }); window.addEventListener('replaceState', function(e) { console.log('change replaceState'); });
總結(jié)
到此這篇關(guān)于js如何無刷新監(jiān)聽URL的變化的文章就介紹到這了,更多相關(guān)js 無刷新監(jiān)聽url變化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- JS如何監(jiān)聽div的resize事件詳解
- JavaScript 監(jiān)聽組合按鍵思路及代碼實現(xiàn)
- JavaScript如何實現(xiàn)監(jiān)聽鍵盤輸入和鼠標監(jiān)點擊
- NodeJS多種創(chuàng)建WebSocket監(jiān)聽的方式(三種)
- JavaScript監(jiān)聽鍵盤事件代碼實現(xiàn)
- 使用JS監(jiān)聽鍵盤按下事件(keydown event)
- js 實現(xiàn)watch監(jiān)聽數(shù)據(jù)變化的代碼
- javascript事件監(jiān)聽與事件委托實例詳解
- 如何用JS實現(xiàn)簡單的數(shù)據(jù)監(jiān)聽
相關(guān)文章
JS基于遞歸算法實現(xiàn)1,2,3,4,5,6,7,8,9倒序放入數(shù)組中的方法
這篇文章主要介紹了JS基于遞歸算法實現(xiàn)1,2,3,4,5,6,7,8,9倒序放入數(shù)組中的方法,涉及JS遞歸算法操作數(shù)組實現(xiàn)排序功能的相關(guān)技巧,需要的朋友可以參考下2017-01-01electron中preload.js文件的用法小結(jié)
preload.js文件在Electron應(yīng)用中起著橋梁的作用,使得在保持安全的同時,渲染進程可以訪問主進程的功能,保持渲染進程與主進程隔離的同時,又能使渲染進程具有訪問特定Electron API的能力的方法,本文給大家分享electron中preload.js文件的用法,感興趣的朋友一起看看吧2024-04-04在SSM框架下用laypage和ajax實現(xiàn)分頁和數(shù)據(jù)交互的方法
今天小編大家分享一篇在SSM框架下用laypage和ajax實現(xiàn)分頁和數(shù)據(jù)交互的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09