Find when Javascript is paused (hard to summarize) [duplicate] - javascript

This question already has answers here:
Start calling js function when PC wakeup from sleep mode
(1 answer)
Can any desktop browsers detect when the computer resumes from sleep?
(6 answers)
Closed 8 years ago.
I'm making a little game out of Javascript, and I'm a little stuck. The game is basically one of those virtual pets, where you have to feed and do stuff with the pet. Now, I have a hunger system made were every 3 seconds the pet gets a little more hungry. The thing is, when I close my laptop, Javascript isn't running. What I'm doing now is getting the date of the last save and getting the difference of that with the current date when I open my laptop.
However, I have no way of triggering the above. I need an event that recognizes when the page comes back up the next time.
If you still don't understand what I'm trying to say, here's an example:
I open up a page and I close my laptop. Javascript has stopped. 30 minutes later, I open it back up and now I get an alert with how long I've been gone. What event can trigger the alert?
BTW, I have tried using such things as onload, onpageshow, etc. All of them either trigger once if not at all.

In advice you to put the current date often (like every 2 seconds). And when you load the page, you refer to this data for seeing how long you're been gone.
http://www.w3schools.com/jsref/event_onload.asp

You do know there is an focus event on the window don't you?
I think it will do what you want
window.addEventListener("focus", function(event) {
// do your thing
}
check this fiddle for an example
http://jsfiddle.net/whQFz/

Related

How to determine that a browser tab is selected and execute code in JavaScript?

I want to have one same page open on multiple browser tabs. When I click on ONE browser tab, I want a JavaScript function to be executed ONCE, just one time! Not that that function is being executed 3 times because that one same page is opened on 3 browser tabs for example.
I have tried:
window.addEventListener("focus", () => {
console.log(document.hasFocus());
});
This works fine if your cursor is focusing on a web browser and keeps switching between tabs on that browser.
But if you first focus your cursor on something else other than that web browser (e.g. computer desktop or code IDE) and then you click on a NON-ACTIVE browser tab, the above code will be executed two times, one time by the previous active tab and another time by the new active tab you just clicked on.
That is my problem.
How can I execute JavaScript code only one time when I click on a web browser tab? Any solution besides JavaScript code is also welcome e.g. tracking pixels or input field autofocus event, just to name samples. I did not mean that tracking pixels techniques will help. I am not using jQuery. I am using VueJs.
You might want to use this ancient method and JS syntax, before you adopt it for your final coding style. Have some classic vanilla flavor. It never hurts.
document.body.onfocus = function(e){console.info(e.type)}
should work exactly as requested...
but since this behavior is somewhat tied to the BOM, some browser vendors (with idiosyncratic behaviors) might require some sort of enforced filtering, Opera comes to mind.
But it should be rock solid on all modern browsers including a bonus backward compatibility, as back as Windows 98 browser version. And\or the ancient and now probably forgoten NN 4.7. ( except for the console info event log, but that's not needed for the actual use anyway )

How to define different messages when Navigation Away and Reloading page? [duplicate]

This question already has answers here:
Identifying Between Refresh And Close Browser Actions
(13 answers)
Closed 6 years ago.
I am currently looking at the "unload" event of a window to try to determine how the "unload" event was triggered, but am having little success. Is there a way to determine how the javascript event was triggered?
Page Refresh
Back Button (or navigate away from the page)
Closing the Browser
Essentially I need to execute some code only when the browser window is being closed, not refreshed or navigated away from.
Purpose: When a customer does an update of our software, the update will redirect their first Internet request to an offer page. There is a button for a "Do Not Bother" option, but some users will simply close their browser. Upon closing the browser, I need to duplicate the "Do Not Bother" functionality so the user no longer gets redirected to the offer page. Simply attaching to the "unload" event will not work due to the different ways of leaving a page.
No, and if there was it would be browser dependent.
What kind of code are you trying to run when the user closes the page?
Is it to logout the user?
Then the user would not be logged out if the browser crashes or the network connection breaks (and probably not if the computer goes to sleep/hibernation mode).
If it is for logout-purposes you should probably use a timestamp variable at the server that gets updated with every request (or use a ajax-ping), and logout the user if it hasn't been seen for a specified time.
Update: Found this answer here at stackoverflow.
Yes, there is a solution!
I've designed a solution based on onBeforeUnload+onLoad events, HTML5 local storage and client/server communication. See the details on https://stackoverflow.com/a/13916847/698168.
I use a method of doing keyboard "sniffing", in that it looks for keydown's of "F5", "ctrl+r", "alt-f4", "backspace" and others, and if it finds them flowing through the keyboard event queue, it sets boolean variables appropriately to trap that status... then I use a "onbeforeunload" function handler, which tests against those boolean status variables to decide what to do.
You can even shut down various keyboard strokes (like "ctrl+n" or "F1" for instance) by using preventDefault(), bubbles=false and returnValue=false in your keyboard handling.
This stuff is not for the faint of heart, but its certainly doable with some persistence and lots of cross browser testing!

How do I handle user leaving/closing the page effectively? [duplicate]

This question already has answers here:
Intercept page exit event
(4 answers)
Closed 9 years ago.
Okay, I have a live application, it runs a messenger and I am trying to find the most reliable way to determine if a user has navigated away from the page or closed the window, et cetera. I have already implemented this:
window.onbeforeunload = function(event){ /* my code */ };
But that isn't always very reliable, sometimes it will fire and sometimes not. Is there a more reliable way of determining user presence or lack thereof?
Have the browser ping the server every X minutes. If you're making a chat client you'll likely have all the infrastructure you need already.

javascript should run only if tab/browser window is focused [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Detect If Browser Tab Has Focus
I have a simple java applet that captures client's screen. With the help of a piece of javascript code, I am able to call the applet and capture the active screen picture.
But, even though it only captures active screen with a click on a button, users are likely to manipulate the process by switching to some other tab with ALT TAB while capture process. I want to make sure that capturing must be done only if page is loaded and page is focused.
So far, I found this piece of javascript code which doesn't seem to be working correctly. Sometimes it gets stuck at the focus even though the page is minimized.
<script language="javascript">
window.onpageshow = function(e) { console.log('pageshow'); };
window.onfocus = function(e) { console.log('focus'); };
</script>
So are there any suggestions to what I am trying to achieve or any other solutions.
Try using document.hidden it's part of the page visibility API

Chrome tab crashing / hanging after brought on foreground being long time on background

I've got a page that shows real-time statistics. It runs a lot of javascript, makes a lot of HTTP requests, renders SVG charts every few seconds using D3.js, has a lot of CSS animations, and rearranges the DOM frequently.
As long as the page is focused, it runs smoothly. If I switch to another tab and come back later, there's often a short pause where the page seems to be frozen before the view suddenly seems to rerender and the page becomes usable again. The longer the tab has been backgrounded, the longer this pause is. If the tab has been in the background for a very long time (hours) and I switch back to it, it will be frozen for a long time then crash.
All these behaviors are observed in Chrome. I haven't tested much in other browsers.
What isn't Chrome doing while the tab is in the background, and what is it doing during that pause when I first switch back to the tab?
UPDATE:
I'm also doing some jQuery animating. This answer and this one may be relevant.
According to that first answer:
"Inactive browser tabs buffer some of the setInterval or setTimeout functions."
stop(true,true) will stop all buffered events and execute immediatly only the last animation.
I've added a call to .stop(true, true) in my code, and at least for short trips away from the tab, I'm not detecting a hiccup. I need to leave it in the background for a long time and test it before I can tell if it made significant difference.
We had a similar issue with SVG graphs and managed to solve it using Page Visibility API introduced with HTML5. If anyone stumbles upon such an issue please refer to the following article Using the Page Visibility API
What we managed to do was to suspend all SVG rendering activities when the browser window is not visible. This managed to stop the tab from crashing.
Yes, it's typical behavior of Chrome browser.
I guess that while your tab is in background, Chrome places all tab data on "back shelf" to clear "front shelf" that works much faster. I know, it sounds unprofessionally, but i hope that you understood.
I think it is very hard to solve this problem in your case (because you are using a lot of manipulations with graphic).. but maybe this method will save you (i had never tested it before):
Every time you update your statistics (or do some highload calculations), you can save a timestamp. Then, when you update your statistics again, you can substract that old timestamp of the new timestamp. And, if you see that the difference between timestamps is very big, use setTimeout() function before next update. Maybe, it will prevent Chrome's chash.

Categories