@jswork/history-observer
v1.0.2
Published
Observe and react to browser history changes.
Readme
history-observer
Observe and react to browser history changes.
installation
yarn add @jswork/history-observerusage
import historyObserver from '@jswork/history-observer';
// 监听所有实际发生的 URL 变化(默认行为:仅当 oldURL !== newURL 时触发)
const unsubscribe = historyObserver.subscribe(({ type, oldURL, newURL }) => {
console.log(`Navigation type: ${type}`);
console.log(`From: ${oldURL}`);
console.log(`To: ${newURL}`);
});
// 示例:触发 pushState(会触发回调)
history.pushState(null, '', '/page1');
// 示例:重复设置相同 URL(不会触发回调,因 URL 未变)
history.pushState(null, '', '/page1');
// 手动取消监听
// unsubscribe();license
Code released under the MIT license.
