As the title suggests, I'm looking to bind a function to the change of the URL query string.
An example:
from: /baby
to: /baby/?_bc_fsnf=1&brand[]=37
To elaborate, I'd want the function to run when the from turns into the to.
Cheers!
As the title suggests, I'm looking to bind a function to the change of the URL query string.
An example:
from: /baby
to: /baby/?_bc_fsnf=1&brand[]=37
To elaborate, I'd want the function to run when the from turns into the to.
Cheers!
If your page is not refreshing, someone is probably calling history.pushState or history.replaceState to change the URL.
There is built-in way to track when pushState and replaceState are called, but you can track them yourself by wrapping each function using this track utility:
function track (fn, handler, before) {
return function interceptor () {
if (before) {
handler.apply(this, arguments)
return fn.apply(this, arguments)
} else {
var result = fn.apply(this, arguments)
handler.apply(this, arguments)
return result
}
}
}
var oldQs = location.search
function handler () {
console.log('Query-string changed:',
oldQs || '(empty)', '=>',
location.search || '(empty)'
)
oldQs = location.search
}
// Assign listeners
history.pushState = track(history.pushState, handler)
history.replaceState = track(history.replaceState, handler)
window.addEventListener('popstate', handler)
// Example code to change the URL
history.pushState(null, 'Title 1', '/baby/?key=value')
history.replaceState(null, 'Title 2', '/baby/?_bc_fsnf=1&brand[]=37')