Javascript time track - javascript

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.

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/

How to limit a javascript function to run max. 1 time a day

When someone visits my site, a certain javascript function must be called. But when they refresh the page, or go to another page, this function should NOT be executed again for at least 24 hours.
Even when the web browser is closed and reopened, the function should not be executed, until it's 24 hours later.
So I was thinking of a Javascript or jQuery function that writes a cookie with a time stamp value when the function is executed.
But before the function is executed, it should check if there is a cookie.
If it's NOT there, execute the function.
If it's there, check the time value in the cookie and compare it with the current time.
Is the time difference 24 hours or more, then execute the function. (and overwrite the cookie time value, for the next 24 hours)
Is the time difference less than 24 hours, do NOT execute the function.
Would this be the right approach to achieve the goal? Or is there a built in function that does this?
And could someone please help me create some javascript or jQuery code to achieve this?
Thank you.
EDIT: I found the following code here: Run code once a day:
<script type='text/javascript'>
function hasOneDayPassed() {
var date = new Date().toLocaleDateString();
if( localStorage.yourapp_date == date ) return false;
localStorage.yourapp_date = date;
return true;
}
function runOncePerDay() {
if( !hasOneDayPassed() ) return false;
alert("blabla");
}
runOncePerDay();
</script>
I tried it. The date value IS stored in local storage. But somehow the function (alert for testing purposes) is still executed when closing and reopening the web browser (while the local storage value is still there)
using cookies or local storage would work, but someone could easily just clear their cookies/local storage or edit the client side code. So if it's really important that they can't re-run the function then you might want to look into storing this information on the server
You might consider doing something like:
function oncePerDay(func){
let dt = new Date, tm = dt.getTime();
if(localStorage.timestamp){
if(tm-localStorage.timestamp > 86399999){
localStorage.timestamp = tm; func(tm);
}
}
else{
localStorage.timestamp = tm; func(tm);
}
}
addEventListener('load', ()=>{
oncePerDay(tm=>{
console.log(tm);
});
});
Of course, if the Client is on the Browser for over 24 hours this won't work without an interval to check for the time change.

Control duration of the session PHP

I am very beginner in web development. I spent some time realizing the way to limit session time in PHP. I have read Stackoverflow suggestions but none of them seems to work for me (cookies-might be edited by user, AJAX communication-extra load on server and static PHP - what about passive tabs in browser? Validation using session vars).
I have in mind this:
<script type="text/javascript">
$(document).ready(function() {
setTimeout(function() {
window.location.href = 'logout.php';
}, 10000);
});
</script>
...to limit session time for users. This system will be used in a management web app. Could anyone point out potential drawbacks of my approach, because it seems to be too simple to be good?
<?php
function check_user_is_valid () {
//Start our session.
session_start();
//Expire the session if user is inactive for 30
//minutes or more.
$expireAfter = 30;
//Check to see if our "last action" session
//variable has been set.
if(isset($_SESSION['last_action'])){
//Figure out how many seconds have passed
//since the user was last active.
$secondsInactive = time()-$_SESSION['last_action'];
//Convert our minutes into seconds.
$expireAfterSeconds = $expireAfter * 60;
//Check to see if they have been inactive for too long.
if($secondsInactive >= $expireAfterSeconds){
//User has been inactive for too long.
//Kill their session.
session_unset();
session_destroy();
}
}
}
//Assign the current timestamp as the user's
//latest activity
$_SESSION['last_action'] = time();
Call check_user_is_valid () function on every php page to check if the user have valid session.It will automatically destroy session if page is still for 30 minutes.
Update the value of $_SESSION['last_login'] variable with new time on every page, so that the user get 30 minutes session for each and every page.

Refresh just home page

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.

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
});

Categories

Resources