How to measure a time spent on a page? - javascript

I would like to measure a time (in seconds in integers or minutes in floats) a user spends on a page. I know there is an unload event which I can trigger when they leave the page. But how to get a time they have already spent there?

The accepted answer is good, but (as an alternative) I've put some work into a small JavaScript library that times how long a user is on 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. The Google Analytics method suggested in the accepted answer has the shortcoming (as I understand it) that it only checks when a new request is handled by your domain. It compares the previous request time against the new request time, and calls that the 'time spent on your web page'. It doesn't actually know if someone is viewing your page, has minimized the browser, has switched tabs to 3 different web pages since last loading your page, etc.
Edit: I have updated the example to include the current API usage.
Edit 2: Updating domain where project is hosted
https://github.com/jasonzissman/TimeMe.js/
An example of its usage:
Include in your page:
<!-- Download library from https://github.com/jasonzissman/TimeMe.js/ -->
<script src="timeme.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.

If you use Google Analytics, they provide this statistic, though I am unsure exactly how they get it.
If you want to roll your own, you'll need to have some AJAX request that gets sent to your server for logging.
jQuery has a .unload(...) method you can use like:
$(document).ready(function() {
var start = new Date();
$(window).unload(function() {
var end = new Date();
$.ajax({
url: "log.php",
data: {'timeSpent': end - start},
async: false
})
});
});
See more here: http://api.jquery.com/unload/
The only caveat here is that it uses javascript's beforeunload event, which doesn't always fire with enough time to make an AJAX request like this, so reasonably you will lose alot of data.
Another method would be to periodically poll the server with some type of "STILL HERE" message that can be processed more consistently, but obviously way more costly.

In addition to Jason's answer, here's a small piece of code that should do the trick if you prefer to not use a library, it considers when the user switch tabs or focus another window.
let startDate = new Date();
let elapsedTime = 0;
const focus = function() {
startDate = new Date();
};
const blur = function() {
const endDate = new Date();
const spentTime = endDate.getTime() - startDate.getTime();
elapsedTime += spentTime;
};
const beforeunload = function() {
const endDate = new Date();
const spentTime = endDate.getTime() - startDate.getTime();
elapsedTime += spentTime;
// elapsedTime contains the time spent on page in milliseconds
};
window.addEventListener('focus', focus);
window.addEventListener('blur', blur);
window.addEventListener('beforeunload', beforeunload);

๐—จ๐˜€๐—ฒ ๐—ฝ๐—ฒ๐—ฟ๐—ณ๐—ผ๐—ฟ๐—บ๐—ฎ๐—ป๐—ฐ๐—ฒ.๐—ป๐—ผ๐˜„()
Running inline code to get the time that the user got to the page blocks the loading of the page. Instead, use performance.now() which shows how many milliseconds have elapsed since the user first navigated to the page. Date.now, however, measures clock-time which can differ from navigation-time by a second or more due to factors such as Time resynchonization and leap seconds. performance.now() is supported in IE10+ and all evergreen browsers (evergreen=made for fun, not for profit). The earliest version of internet explorer still around today is Internet Explorer 11 (the last version) since Microsoft discontinued Windows XP in 2014.
(function(){"use strict";
var secondsSpentElement = document.getElementById("seconds-spent");
var millisecondsSpentElement = document.getElementById("milliseconds-spent");
requestAnimationFrame(function updateTimeSpent(){
var timeNow = performance.now();
secondsSpentElement.value = round(timeNow/1000);
millisecondsSpentElement.value = round(timeNow);
requestAnimationFrame(updateTimeSpent);
});
var performance = window.performance, round = Math.round;
})();
Seconds spent on page: <input id="seconds-spent" size="6" readonly="" /><br />
Milliseconds spent here: <input id="milliseconds-spent" size="6" readonly="" />

I'd say your best bet is to keep track of the timing of requests per session ID at your server. The time the user spent on the last page is the difference between the time of the current request, and the time of the prior request.
This won't catch the very last page the user visits (i.e. when there isn't going to be another request), but I'd still go with this approach, as you'd otherwise have to submit a request at onunload, which would be extremely error prone.

i think the best way is to store time in onload and unload event handlers in cookies e.g. and then analyze them in server-side scripts

According to the right answer I think thats is not the best solution. Because according to the jQuery docs:
The exact handling of the unload event has varied from version to
version of browsers. For example, some versions of Firefox trigger the
event when a link is followed, but not when the window is closed. In
practical usage, behavior should be tested on all supported browsers
and contrasted with the similar beforeunload event.
Another thing is that you shouldn't use it after documents load because the result of substraction of time can be fake.
So the better solution is to add it to the onbeforeunload event in the end of the <head> section like this:
<script>
var startTime = (new Date()).getTime();
window.onbeforeunload = function (event) {
var timeSpent = (new Date()).getTime() - startTime,
xmlhttp= new XMLHttpRequest();
xmlhttp.open("POST", "your_url");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
xmlhttp.send(timeSpent);
};
</script>
Of course if you want to count the time using Idle detector you can use:
https://github.com/serkanyersen/ifvisible.js/
TimeMe is a wrapper for the package that I paste above.

<body onLoad="myFunction()">
<script src="jquery.min.js"></script>
<script>
var arr = [];
window.onbeforeunload = function(){
var d = new Date();
var n = d.getTime();
arr.push(n);
var diff= n-arr[0];
var sec = diff/1000;
var r = Math.round(sec);
return "Time spent on page: "+r+" seconds";
};
function myFunction() {
var d = new Date();
var n = d.getTime();
arr.push(n);
}
</script>

I've found using beforeunload event to be unreliable, actually failing more often than not. Usually the page has been destroyed before the request gets sent, and you get a "network failure" error.
As others have stated, there is no sure-fire way to tell how long a user has been on a page. You can send up some clues however.
Clicking and scrolling are pretty fair indicators that someone is actively viewing the page. I would suggest listening for click and scroll events, and sending a request whenever one is fired, though not more often than say, every 30 or 60 seconds.
One can use a little intelligence in the calculations, eg, if there were events fired every 30 seconds or so for 5 minutes, then no events for 30 minutes, then a couple more events fired, chances are, the user was getting coffee during the 30 minute lapse.
let sessionid;
function utilize(action) {
// This just gets the data on the server, all the calculation is done server-side.
let href = window.location.href;
let timestamp = Date.now();
sessionid = sessionid || timestamp;
let formData = new FormData();
formData.append('sessionid', sessionid);
formData.append('timestamp', timestamp);
formData.append('href', href);
formData.append('action', action || "");
let url = "/php/track.php";
let response = fetch(url, {
method: "POST",
body: formData
});
}
let inhibitCall = false;
function onEvent() {
// Don't allow an update any more often than every 30 seconds.
if (!inhibitCall) {
inhibitCall = true;
utilize('update');
setTimeout(() => {
inhibitCall = false;
}, 30000);
}
}
window.addEventListener("scroll", onEvent);
window.addEventListener("click", onEvent);
utilize("open");

Related

HTML or Javascript for switching url at a specific time

I am from Germany, sorry for my English.
I am searching for a simple HTML or Javascript code to switch to another URL at a specific time.
I Run a landing Page which has an offer thats closed at April 16 at ten o clock for example. I need a little Script or code which directs to another url when the รถfter will be closed.
I am thankful for any help.
Best regards
Marco
If the person has the landing page loaded and is viewing it, and you want to send them to a different URL when the offer closes, you can calculate how much time until that happens when they arrive at the landing page then send them to the new URL when that time is reached.
setTimeout will run a function after a timer has expired, and that function can change the window.location sending them to the new URL.
When the landing page loads get the current time and the time the offer expires:
let now = new Date();
let expires = new Date('2021-04-16 22:00:00');
Subtracting gives you the number of milliseconds until you reach the expires time, which is convenient because that's what the setTimeout function wants for it's "delay" parameter.
Verbosely, this could look like:
const now = new Date();
const expires = new Date('2021-04-16 22:00:00');
const delay = expires - now;
window.setTimeout(function() {
window.location = 'https://example.com/';
}, delay);
<div>
<p>This is the landing page</p>
</div>
This does not loop waiting for time to expire, as DCR warns in a comment; it just sets a timer, which the browser then takes care of.
All the math could be collapsed without using variables, so it becomes
window.setTimeout(function() {...etc...}, new Date('2021-04-16 22:00:00') - new Date());
Here is your script based on your mentioned time. After that specific time, link will be changed automatically.
"https://jsfiddle.net/rounak1/2pxLu5df/2/"
here is the code
let d1 = new Date()
var d2 = new Date('2021-04-16 22:00:00.00');
if (d1 > d2) {
window.location = 'https://www.google.com/'
}
I believe that this problem is better handled by your backend that can redirect the user to another page before the page loads since, if you do this in javascript, the page will have to load first.
However, since you want this to be implemented in Javascript you can do something like below:
var time = moment("16/04/2021 10:00", "DD/MM/YYYY HH:mm");
var now = new Date();
if (time > now) {
window.location.replace("replace with your url"); // Without allowing the user to hit the back button
}
In the above, time stores the datetime when the offer ends in the format enclosed as a string (read about this here: https://momentjs.com/docs/#/parsing/string-format/). This is compared to the time now to implement a redirect.
Read more about the redirect here: https://www.w3schools.com/howto/howto_js_redirect_webpage.asp
The above requires the usage of the moment.js library which you can find here: https://momentjs.com/

Why/How is my code causing a memory leak?

I have written the following JavaScipt code within a Spotfire TextArea. I include the application and tag for completeness, but I don't believe my issue is Spotfire-specific. Essentially, I have a timer which runs every 5 minutes, and clicks on a link (clickLink('Foo');) to trigger execution of some Python code elsewhere in the application. If the application also contains a timestamp of the last full update, which occurs every 30 minutes in the same manner (clickLink('Foo');):
function reportTimestamp() {
var timeNow = new Date();
var hoursNow = timeNow.getHours();
var minutesNow = timeNow.getMinutes();
var secondsNow = timeNow.getSeconds();
return hoursNow + ":" + minutesNow + ":" + secondsNow;
};
function timeBasedReaction(timestampAge){
if (timestampAge >= 1800) {
clickLink('Foo');
clickLink('Bar');
} else if (timestampAge >= 300) {
clickLink('Foo');
};
};
/*
function timeBasedReaction_B(timestampAge){
if (timestampAge >= 300) {
clickLink('Foo');
if (timestampAge >= 1800) {
clickLink('Bar');
};
};
};
*/
function clickLink(linkName) {
var clickTarget = document.getElementById(linkName).children[0];
clickTarget.click();
};
function checkTimestampAge() {
console.log(reportTimestamp());
var myTimeStamp = document.getElementById('Timestamp').children[0]
var timeStampMS = new Date(myTimeStamp.textContent).getTime();
var currentDateMS = new Date().getTime();
var timestampAgeSeconds = (currentDateMS - timeStampMS)/1000;
timeBasedReaction(timestampAgeSeconds);
};
function pageInitialization() {
checkTimestampAge();
var myTimer = null;
var timerInterval = 300000;
myTimer = setInterval(function(){checkTimestampAge()},timerInterval);
}
pageInitialization();
For reasons unclear to me, running this code in the application or in a web browser starts off fine, but eventually leads to very large memory allocation.
I've tried to read
4 Types of Memory Leaks in JavaScript and How to Get Rid Of Them,
JS setInterval/setTimeout Tutorial, and
An interesting kind of JavaScript memory leak, and it's a start, but I don't know enough to really understand what I'm doing wrong and how to correct it.
Thanks, and sorry for the huge block of text.
This causes a memory leak because of how Spotfire handles Javascript which has been associated with/loaded into a TextArea.
Both in the desktop client, as well as in the Webplayer instance, when the page is loaded, all the portions of that page are loaded, include the TextArea and including the Javascript associated therein. My previous understanding in the comments above:
"the code is intended to run when the page loads, and it was my understanding that it would stop/be cleared if the page was re-loaded or someone navigated away from it"
was incorrect. One of the script's actions was to update/redraw the HTML location in the TextArea. This, in turn, reloads the TextArea but does not clear the existing Javascript code. However, it's not really accessible anymore, either, since var myTimer = null actually creates a new myTimer rather than nulling-out the existing one. In this way, instances of myTimer increase geometrically as instances of function timeBasedReaction run and continually update the underlying TextArea and load in more of the same Javascript.
To anyone who ha a similar issue and come here, it's been over 3 months and I haven't figured out how to solve this once and for all. If I do, I'll try to come back with another update.

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 event for mobile browser re-launch or device wake

Morning all, I'm looking for some kind of Javascript event I can use to detect when a mobile browser window regains focus, after either a user closes/minimizes their browser (to go back to a home screen/different app), or if the device resumes from sleep (either the user powering it off, or it going to sleep after a screen timeout).
I'd like to be able to find a single event that works for everything, but I know that's unlikely! The pageshow event works for iOS devices, but it's rather sketchy for use with everything else. I've tried focus and DOMActivate but neither of them seem to have the desired effect.
The page may not always have form elements on it, and I don't really want the user to have to touch the page again to trigger the event.
The requirement for such an event is caused by our code periodically checking for new content by making XHR requests. These are never sent when the browser is asleep, so we never get new content to restart the timeouts.
Thanks for any help you guys may be able to provide!
We had a similar issue and solved it something like this:
var lastSync = 0;
var syncInterval = 60000; //sync every minute
function syncPage() {
lastSync = new Date().getTime(); //set last sync to be now
updatePage(); //do your stuff
}
setInterval(function() {
var now = new Date().getTime();
if ((now - lastSync) > syncInterval ) {
syncPage();
}
}, 5000); //check every 5 seconds whether a minute has passed since last sync
This way you would sync every minute if your page is active, and if you put your browser in idle mode for over a minute, at most 5 seconds will pass before you sync upon opening the browser again. Short intervals might drain the battery more than you would like, so keep that in mind when adapting the timings to you needs.
Better than an interval would be to add a window blur listener and a window focus listener. On blur, record current time. On focus, validate you are still logged in / sync'd / whatever you need to do.
Basically exactly the same thing but it runs only when necessary rather than slowing your entire page down with an interval.
Update
var $window = $(window),
$window.__INACTIVITY_THRESHOLD = 60000;
$window.add(document.body); //necessary for mobile browsers
$window.declareActivity = function () { $window.__lastEvent = new Date(); };
$window.blur($window.declareActivity);
$window.focus(function(){
var diff = (new Date()) - $window.__lastEvent;
if (diff > $window.__INACTIVITY_THRESHOLD) {
$window.trigger("inactivity");
}
});
$window.on("inactivity", "", null, function () {
//your inactivity code
});
Though that blur event seems sketchy if the phone is powering off and I don't know that I would trust it in all circumstances / mobile devices. So I'd probably throw in something like this:
$(document.body).on("click scroll keyup", "", null, $window.declareActivity);
so that my inactivity timer works for when the user just walks away as well. Depending on your site, you may want to adjust that exact event list - or simply throw in a $window.declareActivity(); into your existing scripts that respond to user inputs.

Javascript bookmarklet/iFrame to auto-refresh loaded page if no activity detected within set timeframe?

I have a browser-based application that I use at work (as effectively all corporate apps are now browser-based for obvious reasons) that has an annoyingly short session timeout. I'm not sure precisely what the session timeout is set to, but it's something along the order of 5-10 minutes.
Inevitably whenever I have to use it the session has timed out, I enter the information into the app, submit it, and then the page loads with a brand new session without any of the information actually being passed on - all I get is a new session. I then have to re-enter the information and submit it again in order to have it actually pull up what I want. Of course, I could first refresh the page and then enter the info, but I never know if the session is timed out or not and occasionally it runs painfully slowly so this is a waste of time. Our development team's inability to foresee that little things like this are not only annoying, but also end up costing us a ton of money when you consider the amount of time lost (I work for a VERY large corporation) just waiting for the blasted thing to reload and then having to re-enter the submitted information if a pre-refresh was forgotten as it usually is happens to be beyond me. At some point I'm hoping to become the liaison between the programmers and our customer service body.
Anyway, I digress.
What I'm looking to do is this: I'd like to create a Javascript bookmarklet or something that will automatically refresh whatever page it happens to be on if activity isn't detected within a certain timeframe. This timeframe will be a bit short of whatever I end up figuring out what the session timeout is. Basically I just want to make the page reload itself every, say, five minutes if there hasn't been activity within that period. (I don't want it to refresh out of the blue because the time is up while I'm in the middle of using the app, the only time it should do the auto-refresh is if the app page has been sitting idle)
Can this be done with a Javascript bookmarklet? Should I program a page "wrapper" of sorts that loads the application page within an iFrame or something of the sort? The app site that I use has many subpages, and I'd prefer for it to refresh whatever page I happen to be on at the time if the auto-refresh timeout occurs. Of course, if that isn't possible I'd accept it just reloading the main site page if that's not easily possible since if I've been out of the app long enough for the timeout to happen then I likely don't need to still be on whatever account/page I was on at the time.
Hopefully I've explained myself well enough. The logic is simple - if no activity detected withing x amount of time, refresh the current page is the gist of it.
Thank you, my StackOverflow brethren, yet again for your assistance.
-Sootah
Since I have no ability to influence the coding of the page itself, I've got to have the most simple solution possible. A bookmarklet that times the last refresh/pageload and then refreshes the same page if the timeout is reached would be perfect.
If that's not possible, then if I could write a simple page that I could run from the local computer that'd do the same function by loading the page in a frame or something that'd also be acceptable.
EDIT 10/3/11 7:25am MST
Since I work graves and an odd schedule at work (and this site, unfortunately, being blocked there since it's considered a 'forum' - I work in finance, they're overly cautious about information leakage) before I award the bounty, does one of these event detectors detect the last time the page loaded/? Something like document.onload or whatnot. I'm thinking that setting the timer from the last time the page was loaded is going to be the simplest and most effective approach. My mouse may move over the browser that I have the site open in inadvertently while working on other things, and if the timer resets because of that without me actually having interacted with the site in such a way that a page loads/reloads then the session times out.
This is the bookmarklet code #1 for you, set up to FIVE seconds. Change time to what you like more.
javascript:
(function () {
var q = null;
function refresh() { window.location.reload(); }
function x() { clearTimeout(q); a(); }
function a() { q = setTimeout( refresh, 5000 ); }
document.body.onclick = x;
document.body.onmousemove = x;
document.body.onmousedown = x;
document.body.onkeydown = x;
}())
p.s.: would have been nicer to include eventListeners, but i suppose you need to support IE8, too, so i replaced them with inline events, - if you DON'T need IE8, use code #2:
javascript:
(function () {
var q = null;
function refresh() { window.location.reload(); }
function x() { clearTimeout(q); a(); }
function a() { q = setTimeout( refresh, 5000 ); }
document.body.addEventListener( "click", x, false );
document.body.addEventListener( "mousemove", x, false );
document.body.addEventListener( "mousedown", x, false );
document.body.addEventListener( "keydown", x, false );
}())
edit: in response to comments, here is code #3 with pulling, instead of refreshing page. Yet, despite advices to use iframe, i decided it might be desirable to not execute scripts on that page, so we will use img instead:
javascript:
(function () {
var q = null;
var u = window.location.href;
var i = document.createElement('img');
i.style = "width: 1px; height: 1px;";
document.body.appendChild(i);
function refresh() {
i.src = "";
i.src = u;
x();
}
function x() { clearTimeout(q); a(); }
function a() { q = setTimeout( refresh, 5000 ); }
var evs = ['click', 'mousemove', 'mousedown', 'keydown'];
for( var j = 0; j < evs.length; j++) {
document.body['on'+evs[j]] = x;
}
}())
Create a bookmark and place the code below in the "url" value. Please note that you should change the values of "sessiontimeout" and "checkinterval". They're both in milliseconds.
javascript:(function(){var lastmove = new Date().valueOf(),sessiontimeout=10000,checkinterval=1000;document.onmousemove = function(e){lastmove= new Date().valueOf();};timer = setInterval( function() {var differential = (new Date().valueOf() - lastmove);if (differential > sessiontimeout) {var iframe = document.getElementById("bkmrkiframerefresher");if (iframe) { document.getElementsByTagName("body")[0].removeChild(iframe);} iframe = document.createElement("iframe");iframe.setAttribute("src", "/");iframe.setAttribute("width", 0);iframe.setAttribute("height", 0);iframe.setAttribute("style", "width:0;height:0;display:none;");iframe.setAttribute("id", "bkmrkiframerefresher");document.getElementsByTagName("body")[0].appendChild(iframe);lastmove = new Date().valueOf();} }, checkinterval);})();
This is a bookmarklet that will inject the code below in the page. I tested the bookmarklet in Chrome. It worked on multiple sites except stackoverflow, it seems that they block framing for security reasons. Before you leave your desk, open the website which session you wanna keep alive, then click the bookmarklet on it. Once you're back, refresh the page in order to get rid of the running timers.
The formatted (and commented) code is:
<script type="text/javascript">
// last time the mouse moved
var lastmove = new Date().valueOf();
var sessiontimeout=10000;
var checkinterval=1000;
// reset the last time the mouse moved
document.onmousemove = function(e){
lastmove= new Date().valueOf();
}
// check periodically for timeout
timer = setInterval( function() {
var differential = (new Date().valueOf() - lastmove);
if (differential > sessiontimeout) {
var iframe = document.getElementById("bkmrkiframerefresher");
// iframe already exists, remove it before loading it back
if (iframe) {
document.getElementsByTagName("body")[0].removeChild(iframe);
}
// alert("more than 10 secs elapsed " + differential);
// create an iframe and set its src to the website's root
iframe = document.createElement("iframe");
iframe.setAttribute("src", "/");
iframe.setAttribute("width", 0);
iframe.setAttribute("height", 0);
iframe.setAttribute("id", "bkmrkiframerefresher");
iframe.setAttribute("style", "width:0;height:0;display:none;");
document.getElementsByTagName("body")[0].appendChild(iframe);
// reset counter.
lastmove = new Date().valueOf();
}
}, checkinterval);
</script>
Stefan suggested above that you need no logic besides polling. The edited code is the following:
<script type="text/javascript">
var pollInterval=1000;
timer = setInterval( function() {
var iframe = document.getElementById("bkmrkiframerefresher");
// iframe already exists, remove it before loading it back
if (iframe) {
document.getElementsByTagName("body")[0].removeChild(iframe);
}
// create an iframe and set its src to the website's root
iframe = document.createElement("iframe");
iframe.setAttribute("src", "/");
iframe.setAttribute("width", 0);
iframe.setAttribute("height", 0);
iframe.setAttribute("id", "bkmrkiframerefresher");
iframe.setAttribute("style", "width:0;height:0;display:none;");
document.getElementsByTagName("body")[0].appendChild(iframe);
}
}, pollInterval);
</script>
This code only reload the page once
Here is a bookmarklet(inspired by Kaj Toet's pseudo code), tested in Chrome and Safari, change the timeout value with the var time at the start of the line
Onliner:
javascript:var time = 500; var timeoutFunc = function(){location.reload(true);};timeout = setTimeout(timeoutFunc,time);document.onmousemove = function() {clearTimeout(timeout);timeout = setTimeout(timeoutFunc,time); };
Code
//The time in milliseconds before reload
var time = 500;
//The function that is called when the timer has reached 0
var timeoutFunc = function() {
location.reload(true);
};
//start the timer
timeout = setTimeout(timeoutFunc,time);
//restart the timer if the mouse is moved
document.onmousemove = function() {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunc,time);
};
pseudocode
timeout = settimeout("call",200);
document.onmousemove = function() { timeout = new timeout("call",200); }
function call() {
document.refresh();
}
like this?

Categories

Resources