最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to bind a function to change of URL query string, NOT to hashchange - Stack Overflow

programmeradmin3浏览0评论

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!

Share Improve this question edited Mar 10, 2017 at 20:34 gyre 16.8k4 gold badges40 silver badges47 bronze badges asked Mar 10, 2017 at 19:00 DaneyeDaneye 1,2782 gold badges10 silver badges8 bronze badges 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. – Heretic Monkey 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. – Konstantin Dinev 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. – Daneye Commented Mar 10, 2017 at 19:17
  • I would suggest editing your question to include what you've tried. – Heretic Monkey Commented Mar 10, 2017 at 19:24
Add a ment  | 

1 Answer 1

Reset to default 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')

发布评论

评论列表(0)

  1. 暂无评论