UNPKG

hd-utils

Version:

A handy utils for modern JS developers

32 lines (31 loc) 933 B
import isBrowser from '../validation/isBrowser'; import getWindowObj from './getWindow'; /** * @function onUrlChange * @description -- For Browsers -- * a function that takes callback that will be called whenever the url is changed (ideal for SPA) */ export default function onUrlChange(onPush, onPop) { if (!isBrowser()) return () => { }; const window = getWindowObj(); if (onPush) { (function (history) { const pushState = history.pushState; history.pushState = function () { //@ts-ignore onPush(...arguments); //@ts-ignore return pushState.apply(history, arguments); }; })(window.history); } if (onPop) { window.addEventListener('popstate', onPop); } return () => { if (onPop) { window.removeEventListener('popstate', onPop); } }; }