2

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!

4
  • 1
    A URL change like that is going to refresh the page. There's no binding to that event, unless you monitor onbeforeunload, but that's not going to tell you what URL you're going to, just the one you're on. Commented Mar 10, 2017 at 19:02
  • You have to perform the check every time the page loads and detect whether your query string is not empty. Commented Mar 10, 2017 at 19:03
  • @MikeMcCaughan I'm consoling on doc ready and it's simply not refreshing the whole page. I'm preserving the log and consoling time--never changes. Commented Mar 10, 2017 at 19:17
  • I would suggest editing your question to include what you've tried. Commented Mar 10, 2017 at 19:24

1 Answer 1

9

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')

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.