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/
Related
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
});
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.
Basically, I am designing a quiz application with limited time. Use selects answer to a question and the next question loads using an Ajax request. All questions must be answered within a time frame of, say 2 minutes.
A clock ticks away to show how much time is left and as soon as it hits 0, results are shown. Now since the timer will be implemented using window.setTimeout(), it is possible that the value of timer variable be modified using an external bookmarklet or something like that. Anyway I can prevent this? I think this is implemented on file sharing sites like megaupload. Any forgery on the timer variable results in request for file being rejected.
Have .setTimeout() call an AJAX method on your server to synch time. Don't rely on the client time. You could also store the start time on the server for a quiz, and then check the end time when the quiz is posted.
You need to add a validation in your server side. When the client want to load the next question using an Ajax request, check whether deadline arrived.
The timer in client side js just a presention layer.
If the function runs as a immediately called function expression, then there are no global variables and nothing for a local script to subvert. Of course there's nothing to stop a user from reading your code and formulating a spoof, but anything to do with javascript is open to such attacks.
As others have said, use the server to validate requests based on the clock, do not rely on it to guarantee anything. Here's a simple count down that works from a start time so attempts to dealy execution won't work. There are no global variables to reset or modify either.
e.g.
(function (){
// Place to write count down
var el = document.getElementById('secondsLeft');
var starttime,
timeout,
limit = 20; // Timelimit in seconds
// Function to run about every second
function nextTick() {
var d = new Date();
// Set start time the first time
if (!starttime) starttime = d.getTime();
var diff = d.getTime() - starttime;
// Only run for period
if (diff < (limit * 1000)) {
el.innerHTML = limit - (diff/1000 | 0);
} else {
// Time's up
el.innerHTML = 0;
clearTimeout(timeout);
}
}
// Kick it off
timeout = window.setInterval(nextTick, 1000);
}());
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can you detect/redirect a back button press through javascript?
I am developing a small web application. In my application I must know when the user clicks the "back" button, so I can run some javascript code. Is there any such way to detect it?
thank you
Ok, so I discovered that the JS API cannot access the history object's next property without elevated permissions, which got me thinking in another direction.
Form fields are automatically fetched from the browser's cache, thus holding historic data. while this is true, javascript code is run independently each time.
So I created a small hidden field to hold a timestamp and compare it against the javascript's generated datatime.
Here is the code, I am sure it can be much better implemented, though time is short:
$(document).ready(function () {
var date = new Date();
var clientMiliseconds = date.getTime();
clientMiliseconds = roundTime(clientMiliseconds);
var serverTimeStamp = $('#' + '<%= hfTimeStamp.ClientID %>').val();
serverTimeStamp = roundTime(serverTimeStamp);
alert(serverTimeStamp == clientMiliseconds);
});
function roundTime(time) {
time = Math.floor(time);
//since the server renders the time components a few seconds before the page is downloaded
//which also depends on where you assign the date on the serverside
//we've got a small inaccuracy of few seconds. we neglect these seconds, assuming that it would take the user
//a few seconds to click the back button
time = time / 10000;
time = Math.floor(time);
return time;
}
You can't do that. you can bind an event so that something happens when your user navigates away from the page (use onbeforeunload or unload() to do that) but there is no way to know where he has gone
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");