Is it possible to trigger an event on a website, say 30 seconds after someone hits the site, even if they move between pages, or would that require some server side coding?
Thanks in advance.
You can use session storage to accomplish this. Javascript Storage data persists across pages and refreshes. Here is some info: http://www.w3schools.com/html/html5_webstorage.asp
// SET THIS ON THE FIRST VISIT. CHECK IF ALREADY SET.
if(typeOf(localStorage.getItem('timer')) == 'undefined'){
localStorage.setItem("timer", "0");
}
setInterval(function(){
// ADD 1 SECOND TO SESSION TIMER
localStorage.setItem("timer", localStorage.getItem("timer")++);
if(localStorage.getItem("timer") == 30){
// TRIGGER YOUR EVENT ON 30 SECONDS
}
}, 1000);
Related
I have a website that uses PHP sessions, and I have implemented the following JS code to check every 60 seconds if a user's sessions is still active:
var timeoutInterval = 60000; // 1 minute
function checkTimeout() {
var timeoutWorker = new Worker("/include/cbpull.js");
timeoutWorker.postMessage('/cloud/timeout.php');
timeoutWorker.onmessage = function (result) {
if (result.data['result'] === false) {
location.reload(true);
}
}
}
function sessionTimeout() {
checkTimeout();
setInterval(checkTimeout, timeoutInterval);
}
sessionTimeout();
However, this code crashes the tab in Google Chrome when the session is timed out and location.reload(true) is called. What can I do to make the code work correctly?
Might the following be what's happening? On a session time-out, you reload the page, which immediately triggers sessionTimeout again, which again finds that the session is (still) expired, which reloads the page...
I have set up a function which checks the location of the user every X mins using setInterval() which works for the most part as expected. However after some time of the phone being inactive the intervals seem to stretch out, ie if it was set to 5 mins it could take up to an hour to check again if the phone has been inactive for some time. This is intended to keep going 24/7 so the phone being inactive will be common.
Is this a known problem or is there something I should be doing to prevent this?
var onDeviceReady = function(){
var preCheckGPSInterval = setInterval(function(){
var watchID = navigator.geolocation.watchPosition(
function(position){
if(position.coords.accuracy < 100){
navigator.geolocation.clearWatch(watchID);
//code to execute
}
},
function(error){
console.log("error");
},
{enableHighAccuracy: true}
);
}, 300000);
}
document.addEventListener("deviceready", onDeviceReady, false);
Is this a known problem or is there something I should be doing to prevent this?
#Marty,
this is not a problem. This is the way it is supposed to work. If an App is NOT in the foreground, the app will have it's resources cleared from memory and possibly stored in swap space.
As suggested, you will need to force your app to run in the background. This article will help. 7 things you should know about Android Manifest xml file.
I have a script that uses PHP SESSION. I manage PHP sessions using a class. Within this class I have a method that returns how many seconds remaining before the session expires.
Also, Evey time the user refresh the page or open a new page (new request to the server) the idle time counter starts over $_SESSION['MA_IDLE_TIMEOUT'] = time()+900;
What I am looking to do is display a dialog message 2 minutes before the PHP session expire and check if the user is still on the page or not. If the use clicks "Keep working" then the jQuery script will send PHP AJAX request to renew the session $_SESSION['MA_IDLE_TIMEOUT'] = time()+900;. If the user did not click anything or clicked on "Log out" then the session ends and the user is redirected to the login page.
I did find a nice plugin that will somewhat does the Job jquery-idle-timeout
The issue with this plugin is that it checks if the user is idle using JavaScript (if the keyboard/mouse) are being used. Here is the senario where this script does not help me: lets say my PHP sessions has a limit on 15 minutes/ 900 seconds. A user is reading a super long article on the same page. He/she will be scrolling, they are not really idle "from JavaScript perspective" but from a PHP perspective the use is idle. Then after 20 minutes the user refresh the page, then the user will be logged out since he/she have not sent a new request to the PHP server for over the 900 seconds limit.
How can I solve this problem? is there a better plugin to does the trick? if there something I missed in this plugin that will solve my problem?
Thanks
If the user is not making requests, and is not moving the mouse or keyboard or touching the device, etc., then from the app's point of view the user is "idle" even if their eyeballs are not.
If the user is scrolling you can use javascript to listen for scroll events (via onscroll, for example), but this will not be 100% reliable because (1) depends on javascript, and (2) doesn't work if you are viewing a short article or using a tall/large format monitor (like the ones you can rotate 90 degrees, for example).
Perhaps you could handle this differently: use cookies, single sign-on or similar techniques to pre-authenticate or automatically authenticate requests so that the user's session can safely die and be restarted without the user having to manually login.
The other way you could handle this is to maintain a "ping" process that routinely pings the server (via setInterval(), for example) to keep the session alive, and uses a separate timeout (maybe something like the "Authentication timeout" that ASP.NET uses) to keep track of when the "idle" user should be logged out. Then user actions such as scrolling, requesting pages, focusing in fields, moving mouse, etc., can do a "ping reset" that resets the idle counter to 0.
Example / Concept - leaving as exercise for reader to perfect it:
var idleTime = 0; // how long user is idle
var idleTimeout = 1000 * 60 * 20; // logout if user is idle for 20 mins
var pingFrequency = 1000 * 60; // ping every 60 seconds
var warningTime = 1000 * 60 * 2; // warning at 2 mins left
var warningVisible = false; // whether user has been warned
setInterval(SendPing, pingFrequency);
setInterval(IdleCounter, 1000); // fire every second
function IdleCounter() {
idleTime += 1000; // update idleTime (possible logic flaws here; untested example)
if (console) console.log("Idle time incremented. Now = " + idleTime.toString());
}
function SendPing() {
if (idleTime < idleTimeout) {
// keep pinging
var pingUrl = "tools/keepSessionAlive.php?idleTime=" + idleTime;
$.ajax({
url: pingUrl,
success: function () {
if (console) console.log("Ping response received");
},
error: function () {
if (console) console.log("Ping response error");
}
});
// if 2 mins left, could show a warning with "Keep me on" button
if ((idleTime <= (idleTimeout - (idleTimeout - warningTime))) && !warningVisible) {
ShowTimeoutWarning();
}
} else {
// user idle too long, kick 'em out!
if (console) console.log("Idle timeout reached, logging user out..");
alert("You will be logged off now dude");
window.location.href = "logoff.aspx"; // redirect to "bye" page that kills session
}
}
function ShowTimeoutWarning() {
// use jQuery UI dialog or something fun for the warning
// when user clicks OK set warningVisible = false, and idleTime = 0
if (console) console.log("User was warned of impending logoff");
}
function ResetIdleTime() {
// user did something; reset idle counter
idleTime = 0;
if (console) console.log("Idle time reset to 0");
}
$(document) // various events that can reset idle time
.on("mousemove", ResetIdleTime)
.on("click", ResetIdleTime)
.on("keydown", ResetIdleTime)
.children("body")
.on("scroll", ResetIdleTime);
I use a time cookie to log out an inactive user like this:
`$time = time();
// 5 minutes since last request
if(!empty($_COOKIE['_time'] && $time - $_COOKIE['_time'] >= 300)
{
// log user out
}
setcookie('_time', $time, '/');`
Hope this helps.
Here is my code:
setTimeout(expireAndRedirect(), 200000)
It should call the function expireAndRedirect after 200 seconds.
It works only if it's on the same page on which the above function has been written. But I want it to work on application label.
Is there any way in JavaScript to run a thread after 200 seconds irrespective of on which page you are?
Use html5 local storage to save state between pages and check it on every page load. For example:
Setup:
localStorage.expireAndRedirectAfter = Date.now() + 200000;
setTimeout(function() {
expireAndRedirect();
localStorage.expireAndRedirectAfter = null;
}, 200000);
Check state on each page loading:
if (localStorage.expireAndRedirectAfter) {
if (localStorage.expireAndRedirectAfter > Date.now()) {
expireAndRedirect();
} else {
setTimeout(function() {
expireAndRedirect();
localStorage.expireAndRedirectAfter = null;
}, localStorage.expireAndRedirectAfter - Date.now());
}
}
This solution will work only if all your pages on same domain.
during login set a cookie with current datetime..
next in javascript on every page load check the difference in time and set the expiration accordingly..
Really quick question.
I'm creating a synced streaming app so I would like to emit the current timecode of what's being played every second through socket.io and broadcast it down to other clients.
Is this wise? Are there any drawbacks to making the same call every second, can I make other calls at the same time?
P.S. I'm not making any database calls or doing any processing server-side.
with not to many clients viewing videos it should be fine, but eventually you will experience small lags if the number of users viewing starts to get big.
Another approach is to keep track on server for example you can do this
Video loads with autoplay or emit an event to start a timer server-side
// from client-side
socket.emit('videoplaying',/* some video data */);
on server side you start small timers based on socket IDs
function Timer(VideoInformation){
this.currentTime=0;
this.startedAt=+new Date();
this.endedAt=null;
this.title=VideoInformation.title||'Untitled';
this.interval=null;
this.play=function(){
var self=this;
this.interval=setInterval(function(){ self.currentTime=+new Date(); },1000);
}
this.stop=function(){
if(this.interval!==null){ clearInterval(this.interval) }
}
//.. pause/end/reset ..
}
//server side
var TimeTracker={};
// handling new videoplaying
socket.on('videoplaying',function(videoInformation){
if(!TimeTracker.hasOwnProperty(socket.id)){
TimeTracker[socket.id]=[];
}
TimeTracker[socket.id].push(new Timer(videoInformation));
});
In the end you add event listeners to current video the user is viewing to notify the server timer that it has paused/stopped/click on specific video time etc..
Hope it helps, this isn't a working solution, its more a concept..