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.
If #adrianp is right, you should use window.onbeforeunload.
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 ?
Related
I have a web page that shows remote asset data (for example weather station data) and that does background XMLHttpRequest()'s every 5 seconds to our server and reloads the page if new data from the remote asset has been received. This has all been working fine for years.
The page also has numerous links and submit buttons that can be used to go to other pages or submit commands to the server (which then sends a command to the asset). Issue I'm having is that some of the commands the server then executes involve calls to 3rd party web services, some of which can occasionally take up to 30 seconds to return or time out. But in the meantime if new data came in from the asset the background JS function reloads the page, thereby interrupting and cancelling the new http request that the user initiated.
I could probably work around this by adding onclick or onsubmit tags to every link and submit button to call a function to disable the timer, but as there can be dozens of links on the page I am hoping there might be a simpler, more elegant way where one simple function can tell me if the user clicked on something and thereby initiated a new active http session.
I enable my script by doing a setTimeout('myCheckServerFunction("'+url+'")',5000); from the html head. If the server then tells it there is new data it does a setTimeout(function(){location.reload();},5000);
So I'd like to disable the JS timer and prevent any reload if the user has clicked any link or button and thus if a new http session is active. Does there exist a function like this? eg. something like "window.isNewHttpRequestActive()" ? Or maybe there's a way I can check if the window.location changed? (not sure if that would get updated before the new http request is complete.)
Otherwise I could maybe attach a addEventListener() to every link and submit button on the page but I'm a PHP dev not JS so if anyone could recommend the best way to parse the DOM and attach a listener to every link and submit button that would work too.
I did try looking for events that "bubble" up to higher layers eg. the body element and that will catch link clicks but also catches any click even just a click on any blank area, So not sure how well that would work as I'd still need to filter that event to determine if it actually came from a link or button. Thank you.
Listening to all click events on body isn't necessarily a bad idea.
EDIT: As gre_gor pointed out in comment, it might be. The perceived target of the click is not always the link or button if other elements are inside of them.
So my original method, which was using event.target.tagName is to be avoided.
The following code would add an event listener for click on every a element of the document, and let you cancel the timer if it is set :
for (let element of document.getElementsByTagName("a") {
element.addEventListener("click", (event) => {
if (relocationTimeout !== undefined) {
clearTimeout(relocationTimeout);
relocationTimeout = undefined;
}
});
}
Up to you to adapt the selector in the loop to fit your needs.
Of course don't forget to store the timeout reference in a variable when you set it :
let relocationTimeout = setTimeout(function(){location.reload();},5000)
When I return to a previous page through history.back(), that page is not newly loaded. Instead, it is displayed as it was left. This is good as it is efficient and avoids dribbling in of images.
However, I want to run a function when the page is entered via history.back() to synchronise with the page that is calling history.back(). Is there an event firing in the called page when it is entered in this way [i.e. with history.back()]?
Note: I have a hack using setInterval that polls for re-entry, but think it is ugly. I tried popstate but it did not fire.
You can use
https://github.com/browserstate/history.js/
Especially
History.Adapter.bind(window,'statechange',function()
It fires on every state change ('back' as well).
I'm building a little CoffeeScript application with 10 buttons and a container (simple). When the user press on one of the button : the container change.
The buttons look like a navbar and instead of using links (that will reload the entire page), I used javascript (Coffeescript, jquery or whatever) to change the content of the page (with some Ajax query to load data).
The problem is that the back and forward button of the browser can't work with that solution... and I need to find a solution for that. Routing maybe ?
I really like the way Asana.com resolved this issue: actually the address change but the content seems not to be entirely reloaded.
What do you suggest ? Thanks for the help
Hashes. The simplest solution is to define an URL hash every time the user clicks on a button. For example:
location.href = "#" + button.id;
With that, you create a history entry, and the user can press back or forward in the browser.
But how can you check when this happens? There's the hashchange event:
window.onhashchange = function() {
var state = location.hash.substring(1); // chomps the initial #
...
};
Basing your code on the state variable, you can trigger your AJAX calls from there.
By the way, you can change your code altogether, using links instead of buttons with an hash as the href property, which does not reload the page, but creates an history entry and fires the hashchange event.
The hashchange event is supported by every modern browser (that support history.pushState too, a more flexible and powerful way to control your history) and IE8-9.
I'm creating a homepage. The content of the page is only get by HTTP-Request. So that the Client never change the page-url. How can I catch the back() function from the Browser to go one step back in my HTTP-Request. The automaticly creating of History of all loaded HTTP-Request is done, maybe I must catch this back() function.
Thanks for Help
You might want to update the hash (www.mysite.com/#hash) and then use a mechanism to detect hash change.
Try using this: Browser Back Button Detection
As far as I'm aware you cannot interfere with the back button etc. as it affects the browsers UX.
The best way would probably be to catch the browsers 'onunload' event which is triggered when the page is left. You could write a custom handler function on the assumption that they are clicking back.
If you want to get the page the user come from, you can use the document.referrer (more info on getting last page URL from history object - cross browser?).
Then you could use this to create a link if needed.
Regards,
Max
I have a webpage that use $(document).ready() to build the interface. Then the user can go to a child page, and to go back to the original page he can press the browser's "previous" button or a "Return" button in the page which triggers a history.back();. Back on the original page, $(document).ready() is not triggered so the page is missing information.
Is there a way to trigger it automatically like if it was a "real load"?
edit
placing an alert in it, the alert is popped but stuff is missing in my interface like if some part of the ready event is missing. Investigating...
edit 2
hahahahaha in document.ready I click some checkbox which are supposed to be unchecked. When I "back" on this page, they are checked so they become unchecked because I reclick them.
Sorry, this is completely my bad :(
A quick solution to this problem, use "onpageshow" instead.
window.onpageshow = function(event) {
//do something
};
If the user uses the Back button to navigate and you require a full reload of the page, you can set the NO-CACHE policy of the page.
This way the browser is forced to reload the page from the server, even using the Back button.
1.) put scripts at the bottom of your page.
2.) execute plugins and whatnot in your last script tag(s).
3.) Do not use onDomReady implementations at all, it's redundant.
People are so accustomed to onload or ondomready, they overlook the fact that putting your scripts at the bottom of a page does virtually the same thing without the need to poll and see if your html is available.
Furthermore, it's also good practise as your scripts do not block html/css rendering either.
Not depending on onDomReady or onLoad implementations solves a lot of issues.
Very interesting question. You might need to re-trigger the event/function when the page gets focus, or something similar. you might also need to keep a flag variable to track whether an 'event re-triggering' is in order.