0

The following doesn't work:

$(window.document.location).change(function (){

});

How do I know when to start sending data back to the server?

UPD: Yes, i want to detect when the user leaves or refresh current page. Thanks! A window.onbeforeunload what I was looking for.

Sasay
  • 101
  • 3
  • 11
  • what do you think `window.document.location` is an `object` or `string` – Rafee May 14 '13 at 07:33
  • Just to clarify, you want to detect when the user leaves the current page? – adrianp May 14 '13 at 07:33
  • May be these answers will help you out: http://stackoverflow.com/questions/7317273/warn-user-before-leaving-page-with-unsaved-changes and http://stackoverflow.com/questions/1244535/alert-when-browser-window-closed-accidentally – Sachin Jain May 14 '13 at 08:00

2 Answers2

2

If @adrianp is right, you should use window.onbeforeunload.

Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
  • 1
    Still, this is not always reliable; OP's question is not very clear, but the best option is usually to send the data as soon as you have it. – adrianp May 14 '13 at 07:55
  • Exactly. Perhaps, with a smallish delay to reduce the server load/traffic. This is what e.g. Google apps do. onbeforeunload is mostly used to avoid losing entered data (e.g. an unfinished StackOverflow answer :)) – Alexander Pavlov May 14 '13 at 08:13
0

There is no event for a location change (there is for hash change though, see "hashchange"), so you would have to use polling to keep track of the location by checking in intervals.

You could track clicks on anchors inside your page and prevent the default behaviour occuring (i.e. the browser loading the new page and possibly halt executing the remaining JavaScript in the event handler) so you can delay the page change and execute whatever logic your application requires before the document is unloaded (which would fire an unload event).

Which brings me to the question : what do you intend to do ?

Igor Zinken
  • 884
  • 5
  • 19