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.
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 have a pop up form on my site which pops up as soon as some one click on the link. but I want to make it such that it should not pop up for the second time for a same user.
how to do it, as I don't have user management system.
Even better Solution,Use one in Jquery
<a id="popup" >link1</a><br>
$('#popup').one('click',function(){
alert('open your popup here');
});
Here is you fiddle
You need to use cookies for it. At first click, generate a cookies when user clicks at first time and checks if it's available when user click on it.
So, as kind of solution u can use cookies. Example below.
This support function will help u get cookie using JS later
function getCookie(name) {
var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,'\\$1')+"=([^;]*)"));
var x = matches ? decodeURIComponent(matches[1]) : undefined;
return x;
}
And than in user click handler set cookie for browser like this
$(document).on('click','#someDivHere',function() {
if (getCookie('addShowed') === undefined) {
var date = new Date( new Date().getTime() - 2*24*60*60*1000 );
document.cookie="addShowed='true'; path=/; expires="+date.toUTCString();
}
});
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
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 web-application for iPhone, and I need to trigger a Javascript function when the web page is in focus, in other words, when Safari is open.
What I want to accomplish is to start a timer in some way when the user clicks on a tel-link and starts the call. When the call ends, Safari pops up again, and the timer ends.
Is there any way to do this?
Best Regards
Linus
try this:
if you trigger the link for the call set the actual time in a localStorage-item.
$("#yourButton").click(function() {
var actualTime = new Date().getTime();
window.localStorage.setItem('callStart', actualTime);
})
after that you need to read the Storage after user ends up the call.
You can set this in the document.ready on the opening page.
in $(document).ready(function() {})
// check for the localStorageItem
if (window.localStorage.getItem('callStart')) {
// get it
var timeStart = window.localStorage.getItem('callStart');
var now = new Date().getTime();
/*
Now calculate here the difference now - timeStart
and you will get seconds, minutes or whatever you want
*/
// !!! Dont forget to clear the localStorageItem
window.localStorage.removeItem('callStart');
}
This is what I would try. The Usage of the HTML5-localStorage gives you the possibility to store key/values and data isnt lost if user stops the app or device is automatically locked.
Hope this helps a bit.
ADDED: You even can store JSON as the value in the localStorageItem. So you can set an callID and implement a calling-history for your users.