3

Is there any way to do something like this: $(window).on("hashchange", doSomething); but detect document.location.search change?

wxs
  • 5,617
  • 5
  • 36
  • 51
Dmitry
  • 4,143
  • 10
  • 46
  • 57

3 Answers3

2

This was already asked in On - window.location.hash - change?. In a nutshell, there is no perfectly clean way to do this in JavaScript; you would need to be checking the location every now and then. Some frameworks and libraries will give you a nice abstraction layer over this but internally, they just keep polling the location.

Unfortunately, Lucas' answer is incorrect - you can use the JavaScript History API to modify the current URL without reloading the page.

unpollito
  • 937
  • 1
  • 11
  • 30
  • @dmitrymar is not trying to change the URL without reloading. Instead, he is trying to detect a change due to a user's action, in which case the History API would be useless. – Lucas Rodrigues Oct 27 '15 at 19:39
  • Why doesn't anyone realise this is a quality answer? You CAN change the search param WITHOUT reloading the page... – brandito Jun 15 '18 at 03:26
1

The hash and the search tag are having different implementation. When the search string got changes the whole page got reloaded but not in the case of hash. So if you want to do some processing on href change then you can use the onbeforeunload event handler.

You can use the beforeunload event to trigger your code to run prior to navigation... If you need something more specific (e.g., only navigations initiated in your code), then I recommend that you factor out code changing window.location into a separate function, and add a hook for your custom logic.

For better understanding you may want to look at Ben Nadel's post in regard to doing this, it may be exactly what you're looking for.

Raju Bera
  • 948
  • 8
  • 14
-1

Differently from what happens with hash, if your search value changes due to a user's action, your page will get reloaded. Therefore, your option would be to use the onbeforeunload event:

<body onbeforeunload="return myFunction()">

http://www.w3schools.com/tags/ev_onbeforeunload.asp

Lucas Rodrigues
  • 1,234
  • 2
  • 11
  • 22