Refresh just home page - javascript

I am currently designing a system which includes a homepage that show the person who logs in only the work they have to do. I have been asked to set up this homepage to refresh every 3 minutes which I have done using this code:
function startTimer() {
var now = new Date();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var secTime = minutes*60*seconds;
if(secTime % (3*60) == 0){
var refreshTime = 3*60*1000;
} else {
var refreshTime = (secTime % (3*60)) * 1000;
}
setTimeout('refresh()', refreshTime);}
function refresh() {
window.location.href = 'myURL';
}
startTimer();
The problem I currently have is that when I navigate away from this page, but still in the system, it keeps returning me to homepage and I lose what I am working on.
Is there a way that I can keep refreshing homepage for those who haven't moved away from it and stop it when someone does?
I am very new to Javascript so please be patient if I ask a lot of question.
Thank you in advance for any help given.

I assume you are using a shared javascript file on all pages of the site which is why the timer will keep running on every page. You could make sure that the timer only runs on the homepage by checking the page url and wrap your startTimer function inside this check:
if (document.location.href == "http://www.yourhomepage.com"){
startTimer();
}
Replace http://www.yourhomepage.com with whatever url your homepage is on. This will only work if your pages are separate html files. If you are using a hashbang method whereby the document doesn't change, this will not work.

You can use Ajax to refresh the work log part of the page instead of refreshing the whole page.

When you refresh your page, your code redirect you to your home page because of window.location.href = 'myURL';. The location change, and it redirect you everytime to 'myURL'.
You would like to refresh only a part of your page. You have to send a XMLHttpRequest or Ajax request ( you load a page into your current page without reloading your current page ). https://developer.mozilla.org/fr/docs/XMLHttpRequest
When you get the page loaded, you insert the text loaded into the page.
Then, call the function which send request, every "refreshTime" like that
function sendAjax(){
// ... ajax request
// refreshTime = 3 * 60 * 1000;
setTimeout( sendAjax, refreshTime );
}
sendAjax();
Don't use quote arround the function name in setTimout. setTimemout need a function to call (not his name but his value) and time parameters.

Related

How to automatically reload a web page

I want my website page to reload once when it has already opened for the first time. I wrote this function in my javascript file for that...
var i;
$(document).ready(function(){
for ( i=0;i<1;i++){
if(i===0){
location.reload();
break;
}
}
});
But the page keeps reloading again and again as if the above function was a recursive one.
How do I do this?
P.S I'm doing it because of this issue.
<script type='text/javascript'>
(function() {
if( window.localStorage ) {
if( !localStorage.getItem('firstLoad') ) {
localStorage['firstLoad'] = true;
window.location.reload();
} else
localStorage.removeItem('firstLoad');
}
})();
</script>
Here is what's happening:
The page loads for the first time, jQuery calls any handlers on the document.ready event
The page reloads
The document.ready call is made again
repeat
Out of curiosity, why would you want to do that? And why do you have a for loop that will run for one iteration?
Also, to answer your question as far as I know the only way to make sure the page doesn't reload is use a cookie that lasts for about 5 seconds. Then, on document.ready check for that cookie and if it exists then don't reload.
You must either set a cookie (or use javascript's localStorage), or use xhr to retrieve a value held on a remote server.
If you want to use cookies, it's as simple as
document.cookie = "username=John Doe";
where the document.cookie is a query string of the form (x=y;a=b;n=z)
If you want the page to reload every time the user vists, be sure to unset the cookie once you've done any necessary processing when a page reload has been set.
$( window ).load(function() {
if (window.location.href.indexOf('reload')==-1) {
window.location.replace(window.location.href+'?reload');
}
});
Code is ok. But if the page is opened from another page with a link to an id (.../page.html#aa) the code only works with firefox. With other browsers reload the page without going to id. (Sorry for my english).
I found the solution with this code. It is assumed that the page is refreshed no earlier than one hour. Otherwise, add minutes to the oggindex variable.
<script>
var pagina = window.location.href;
var d = new Date();
var oggiindex = d.getMonth().toString()+'-'+d.getDate().toString()+'-'+d.getHours().toString();
if (localStorage.ieriindex != oggiindex)
{
localStorage.setItem("ieriindex", oggiindex);
window.location.replace(pagina);
}
</script>
Yours code executed each time $(document).ready(), so it's not surprise that your loop is infinity - each load finished as ready state.
If you give more detailed requirements we can solve it with no using window object as data holder. It's bad way but you can set it for test.
Window object stores variables not depend on reload because it's higher then document.
Let's try:
if( window.firstLoad == undefined ){
// yours code without any loop
// plus:
window.firstLoad = false;
}
You can make it with localStorage API.
Check this link also, it's giving more information about window object variables:
Storing a variable in the JavaScript 'window' object is a proper way to use that object?

How to reload page when jquery.counter trigger finish.countdown event for multiple instance?

I am using multiple instance for jQuery countdown and implement page reload when counter get finished
E.g.
$('.countdown').each(function() {
var $this = $(this),
finalDate = $(this).data('countdown');
$this.countdown((finalDate), function(event) {
var days = event.strftime('%D');
$(this).find('.days').children('span').html(days);
$(this).find('.hours').children('span').html(event.strftime('%H'));
$(this).find('.minutes').children('span').html(event.strftime('%M'));
$(this).find('.seconds').children('span').html(event.strftime('%S'));
});
$(this).on('finish.countdown', function(event){
/*if(!window.location.hash && !(window.location.hash.indexOf('_loaded') > -1)) {
window.location = window.location + '#_loaded'; window.location.reload();
}*/
//If I put window location reload here it will goes into infinite loop. Also above commented code will reload page twice initially which is also not valid solution.
});
});
Issue: If countdown is already finished (E.g. 00:00:00:00 ) then page reload occur twice when script loaded at first time,
I have used localStorage concept but unable to find exact solution. Please help
I had almost this issue with page constantly reloading instantly.
Try and check if your local time and server time are the same. In my case, the difference was two hours, which was the issue that put the page into constant loop.
Countdown plugin has some notes on timezone awareness: http://hilios.github.io/jQuery.countdown/examples/timezone-aware.html

How to create a javascript timer?

I want to start/display a timer on submit button event. I am using spring mvc. So on submit, it goes to the controller, performs some logic and gets redirected back to the original jsp page.The problem is the timer gets reset on page load when its redirected from controller.Once the timer is started, it shouldn't be reset until a stop timer button is clicked. How can i implement this functionality?I am using a jquery timer plugin, but its not quite working.I tried adding a counter=0 value, its not right either.
This is my code:
var counter=0;
function updatecounter(){
counter = 1;
Example1.init();
}
var Example1 = new (function() {
var $stopwatch,
incrementTime = 70,
currentTime = 0,
updateTimer = function() {
$stopwatch.html(formatTime(currentTime));
currentTime += incrementTime / 10;
};
this.init = function() {
$stopwatch = $('#stopwatch');
Example1.Timer = $.timer(updateTimer, incrementTime, true);
};
this.resetStopwatch = function() {
currentTime = 0;
this.Timer.stop().once();
};
if(counter!=0){
$(init);
}
});
HTML markup:
<h2><span id="stopwatch">00:00:00:00</span></h2>
<input type="submit" value="Run Script" name="Run Script" class="button"onclick='updatecounter();' />
<input type="submit" value="Stop Script" name="Stop Script" class="button" onclick='Example1.resetStopwatch();/>
I'm not going to try to create an entire application stack, so I'll keep this simple.
If you MUST redirect to the Spring Controller, then you're going to have to
Pass the start time from the page back to the controller
Pass that same start time from the controller back to the original page
Check for the start time when the page loads and
Start the timer
Add time to the timer equal to the difference between the start time reported from the server and now
So in pseudo-code:
if( startTime IS set ){
timer.start();
timer.setStartTime( startTime );
}
And this would assume that your timer simply calculates a difference from the start time to display a count.
However, the much better option would be for the page to NOT redirect to the server.
Just send off an AJAX request and let it come back whenever, and you can have your timer running the whole time.
This makes the most sense because the very nature of your question ("I need this thing to happen at the same time another thing is happening!") screams Asynchronous, which is the A in AJAX.
Try what this person recommends.
Session variables
Ok Finally i figured a way to fix it..On submit, I created a flag on server side and pass it to the jsp on page load. Based on the flag, it automatically starts the timer.Since its a quick process,( forward to controller and redirect back to jsp) the time delay is negligible.

Is it possible to know how long a user has spent on a page?

Say I've a browser extension which runs JS pages the user visits.
Is there an "outLoad" event or something of the like to start counting and see how long the user has spent on a page?
I am assuming that your user opens a tab, browses some webpage, then goes to another webpage, comes back to the first tab etc. You want to calculate exact time spent by the user. Also note that a user might open a webpage and keep it running but just go away. Come back an hour later and then once again access the page. You would not want to count the time that he is away from computer as time spent on the webpage. For this, following code does a docus check every 5 minutes. Thus, your actual time might be off by 5 minutes granularity but you can adjust the interval to check focus as per your needs. Also note that a user might just stare at a video for more than 5 minutes in which case the following code will not count that. You would have to run intelligent code that checks if there is a flash running or something.
Here is what I do in the content script (using jQuery):
$(window).on('unload', window_unfocused);
$(window).on("focus", window_focused);
$(window).on("blur", window_unfocused);
setInterval(focus_check, 300 * 1000);
var start_focus_time = undefined;
var last_user_interaction = undefined;
function focus_check() {
if (start_focus_time != undefined) {
var curr_time = new Date();
//Lets just put it for 4.5 minutes
if((curr_time.getTime() - last_user_interaction.getTime()) > (270 * 1000)) {
//No interaction in this tab for last 5 minutes. Probably idle.
window_unfocused();
}
}
}
function window_focused(eo) {
last_user_interaction = new Date();
if (start_focus_time == undefined) {
start_focus_time = new Date();
}
}
function window_unfocused(eo) {
if (start_focus_time != undefined) {
var stop_focus_time = new Date();
var total_focus_time = stop_focus_time.getTime() - start_focus_time.getTime();
start_focus_time = undefined;
var message = {};
message.type = "time_spent";
message.domain = document.domain;
message.time_spent = total_focus_time;
chrome.extension.sendMessage("", message);
}
}
onbeforeunload should fit your request. It fires right before page resources are being unloaded (page closed).
<script type="text/javascript">
function send_data(){
$.ajax({
url:'something.php',
type:'POST',
data:{data to send},
success:function(data){
//get your time in response here
}
});
}
//insert this data in your data base and notice your timestamp
window.onload=function(){ send_data(); }
window.onbeforeunload=function(){ send_data(); }
</script>
Now calculate the difference in your time.you will get the time spent by user on a page.
For those interested, I've put some work into a small JavaScript library that times how long a user interacts with a web page. It has the added benefit of more accurately (not perfectly, though) tracking how long a user is actually interacting with the page. It ignore times that a user switches to different tabs, goes idle, minimizes the browser, etc.
Edit: I have updated the example to include the current API usage.
http://timemejs.com
An example of its usage:
Include in your page:
<script src="http://timemejs.com/timeme.min.js"></script>
<script type="text/javascript">
TimeMe.initialize({
currentPageName: "home-page", // page name
idleTimeoutInSeconds: 15 // time before user considered idle
});
</script>
If you want to report the times yourself to your backend:
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","ENTER_URL_HERE",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
xmlhttp.send(timeSpentOnPage);
TimeMe.js also supports sending timing data via websockets, so you don't have to try to force a full http request into the document.onbeforeunload event.
The start_time is when the user first request the page and you get the end_time by firing an ajax notification to the server just before the user quits the page :
window.onbeforeunload = function () {
// Ajax request to record the page leaving event.
$.ajax({
url: "im_leaving.aspx", cache: false
});
};
also you have to keep the user session alive for users who stays long time on the same page (keep_alive.aspxcan be an empty page) :
var iconn = self.setInterval(
function () {
$.ajax({
url: "keep_alive.aspx", cache: false });
}
,300000
);
then, you can additionally get the time spent on the site, by checking (each time the user leaves a page) if he's navigating to an external page/domain.
Revisiting this question, I know this wouldn't be much help in a Chrome Ext env, but you could just open a websock that does nothing but ping every 1 second and then when the user quits, you know to a precision of 1 second how long they've spent on the site as the connection will die which you can escape however you want.
Try out active-timeout.js. It uses the Visibility API to check when the user has switched to another tab or has minimized the browser window.
With it, you can set up a counter that runs until a predicate function returns a falsy value:
ActiveTimeout.count(function (time) {
// `time` holds the active time passed up to this point.
return true; // runs indefinitely
});

Javascript time track

my requirement is 15 minutes after visiting the site, user will navigate to registration page. And I need to track the page even after open that page again, user will navigate to registration page.
As the requirement I think it will be possible with cookie, but I need to count the time of visiting the site. When site visiting minutes reach to 15 js will fire a function and there I can set the cookie and redirect.
Can any one please help me to track the site visiting minutes by js?
Although I agree with epoch, it can be done using localStorage:
(function (timer)
{
var now = new Date();
var redirect = function()
{
location.href = 'register url';
}
if (!localStorage.getItem('registrationMinutes'))
{
localStorage.setItem('registrationMinutes',(+now)+60000*15);//time +15 minutes
}
if (localStorage.registrationMinutes <= +now)
{//on page load, check if 15 mins are up
return redirect();
}
timer = setTimeout(redirect,localStorage.registrationMinutes - now);//call function when time is up
})();
Just include this little function on all pages. You might want to set a cookie like userIsRegistered, and not set the timeout when the client has already been registered.Just know that this code will be sent to the client, and he or she is still free to disable cookies, JS,... and, I think, localStorage isn't supported by older IE browsers (there's a surprise!)If all this is a bit much, here's a simple copy-paste snippet:
(function (url,now,timer)
{
var redirect = function()
{
location.href = url;
}
if (!localStorage.getItem('registrationMinutes'))
{
localStorage.setItem('registrationMinutes',(+now)+60000*15);//time +15 minutes
}
if (localStorage.registrationMinutes <= +now)
{//on page load, check if 15 mins are up
return redirect();
}
timer = setTimeout(redirect,localStorage.registrationMinutes - now);//call function when time is up
})('redirectUrl',new Date());
just replace the 'redirectUrl' string with your url, and it should work just fine. There is also no need to change variable names: it's all contained in this anonymous function's scope, so there is no conflict with variables declared in the parent scope.

Categories

Resources