I have a web page where the data gets updated upon refresh.
I want the user to when the page has been refreshed lastly.
ie if i refresh the page after 3 sec, it should display 3 sec and so on....
Example:
var current = "08/06/2014 15:00:00"; // Current time
var next = "08/06/2014 15:00:30"; //Time after Refresh
It should output
Last seen:30 sec // (15:00:30 - 15:00:00)
Is there any way to get time after refresh using javascript??
You can use HTML5 LocalStorage or Cookies for storing last seen date, example(uses LocalStorage, save last page open date and show this on next loads):
window.onload = function() {
var lastSeen = localStorage.getItem("lastSeen");
if (lastSeen) {
alert("User last seen in " + lastSeen);
} else {
alert("User first time logged in page")
}
localStorage.setItem("lastSeen", new Date());
};
See this example on jsFiddle
Related
Hello I am new in javascript, I am making chrome extension, this extension contains the setInterval command, I want to change the time with javascript to the textbox I have added to a website. This change should remain when I refresh the page, how can I do this.
My content script start document_end
var Refresh = setInterval(clickerStart,4000)
function clickerStart(){
var selection1 = document.querySelector("#\\30 ") !== null;
if (selection1) {
location.reload();
} else {
console.log("Islem Bulundu.");
};
}
//textbox
var Interval = document.createElement("INPUT");
Interval.setAttribute("type", "text");
Interval.setAttribute("value", " ");
document.body.appendChild(Interval);
If you are not handling with sensitive data, which I think it is the case, you can use localStorage or cookies to store and reuse data (the interval time) until the user returns to the page (after refreshing it or reopening it).
Here's an explanation on how to set cookies:
https://www.w3schools.com/js/js_cookies.asp
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.
I store my webpage info in the URL hash, including page number. In order to ensure the page does not exceed the total pages I added this condition. assuming total pages = 10
//get page value from URL
function getParams(val){
return decodeURI(
(RegExp('[#|&]' + val + '=' + '(.+?)(&|$)').exec(location.hash)||[,''])[1]
);
}
var totalPages = 10;
$(window).on('hashchange',function(){
if(getParams('page') > totalPages){
window.location = "#page=1";
}
});
the problem is that if the page loads from another time where the total pages were more:
www.website.com#page=11
it redirects to page 1, but then if the user navigates back, it goes back to page 11 for an instant then redirects back to page 1 and gets trapped in that cycle, making it impossible for the user to navigate back. is there any way to prevent this problem? thanks for reading.
I've encountered a similar problem before, use window.location.replace(url) instead of window.location = url; so that the previous page will not be saved in the session history.
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
});
I have a simple user survey form in which there is one section where the user needs to click on a link, read the page inside the link and then come back to continue the form. Currently, I have a parent HTML page from which I am providing a link to open a child web page in a different window/tab.
How can I obtain the time the user spent on the child window/tab?
listen to the user's click by something like
$('a').on('click', function(){
var d = new Date();
var curr_time = d.getTime();
//save in cookie1
})
and now in the other html page where the user is reading....do the same thing but only on window's unload
$(window).unload(function(){
var d1 = new Date();
var curr_time1 = d1.getTime();
//save in cookie2
})
save this also....
then when s/he comes back I mean on its onfocus you can subtract the values of these 2 cookies and divide by 1000 to get seconds as these time will be in milliseconds.
(cookie1 -cookie2)/1000 seconds //if the cookie thing is used
Does the user leave the page by clicking on the link, or is the second page displayed inside the first one? In the first case, you'll have to use a cookie to store the click time, in the second case, use a variable. Time can be retrieved using new Date().
Record the time of window open
Open the page in a named window
Set a timeinteval function (on original page) to check the location.href of the named window of say 1000 ms
if changed (to a finished/thankyou page) or not existing user must have finished reading
You should set a cookie or an DOM storage value while the page-to-read is open. In that page:
var isFocused = true; // just opened
var secondsLookedupon = 0; // eventually init with a saved value
window.onblur = function(){ isFocused=false; }; // use addEventHandler and co
window.onfocus = function(){ isFocused=true; }; // use addEventHandler and co
window.setInterval(function(){
if (!isFocused) {
secondsLookedupon++;
document.cookie.name = secondsLookedupon; // set a cookie in some way
window.sessionStorage.setItem("name", secondsLookedupon); // or use DOM storage
}
}, 1000);
and from the survey form page you can read that value from the cookie or domstorage whenever you need.