Checking if a page is up prior to loading the page - javascript

We need a solution to the following issue.
We currently refresh a screen every 30 seconds, what we need to do prior to the actual refresh is check if the website is still up and if there is a network present to access the page.
If the page is down then we delay the refresh by 6 seconds this is repeated 5 times.
If the fifth attempt is showing that the website is still down then an error message is displayed.
This is working fine but we need to check if the website is still available (ping the website prior to refreshing) and also we need a solution if the browser starts to refresh but loses the connection or the server goes down once the refresh has started
This is the current code
window.onload = function () {
var refresh_rate = 30; //<-- Second until refresh
var connection_attempts=5; ////// Connection attempts
var failed_seconds=6;
var inactivity_counter = 0;
var connection_failed= 0;
function reset1() {
inactivity_counter = 0;
console.log("Reset1");
}
function reset2() {
inactivity_counter = 0;
console.log("Reset2");
}
function reset3() {
inactivity_counter = 0;
connection_failed = 0;
console.log("Reset3");
}
function reset_network() {
inactivity_counter = (refresh_rate - failed_seconds);
console.log("ResetNetwork");
}
setInterval(function () {
inactivity_counter++;
refreshCheck();
}, 1000);
function can_i_refresh() {
if (inactivity_counter >= refresh_rate) {
return true;
}
return false;
}
function refreshCheck() {
if (can_i_refresh()) {
if(navigator.onLine) {
connection_failed='0';
window.location.href='alreadybooked.php?location=5';
inactivity_counter = 0;
}
else {
connection_failed++;
console.log(connection_failed);
if(connection_failed==connection_attempts) {
alert("Error 1001: This check-in device is currently experiencing issues. Please check-in on another device. If you still experience issues, please press the 'OK' button and proceed to reception");
return false;
}
reset_network();
}
}
else {
console.log(inactivity_counter);
}
}
window.addEventListener("click", reset1);
window.addEventListener("mousemove", reset2);
};

This should do what you need.
The function setupPageReload() creates a timeout so that the page reload will start after the specified delay. The actual reload is done into a temporary element, so the check for availability and the reload are the same thing. If the reload doesn't happen (for any reason) then the fail counter is incremented and will execute the fatalError() function if there have been enough retries. If it works then it simply replaces the contents of the current page with the contents that were just downloaded. Unless there was a "fatal error" then the function is simply executed again to start the process all over.
var refreshRate = 30;
var connectionAttempts = 5;
var connectionFailed = 0;
function setupPageReload() {
setTimeout(function() {
$("<div/>").load(location.href + " body", function(response, status) {
if (status == "success") {
connectionFailed = 0;
$("body").html(response);
setupPageReload();
}
else {
if (++connectionFailed === connectionAttempts) {
fatalError();
}
else {
setupPageReload();
}
}
});
}, refreshRate * 1000);
}
function fatalError() {
alert("Error 1001: This check-in device is currently experiencing issues. " +
"Please check-in on another device. If you still experience issues, " +
"please press the 'OK' button and proceed to reception");
}
window.onload = setupPageReload;
Incidentally, this method requires jQuery as that performs the ajax download and gets the content of the <body/> tag much, much easier than if you were to do that in vanilla js. If you don't already use that in the page in question then you'll need to add a script include.

Related

Auto Logout user when a tab is closed or browser closed from task manager in codeigniter

Following is my code that I'm using to logout user after 10 mins of inactivity.
var timer = 0;
function set_interval() {
timer = setInterval("auto_logout()", 300000);
}
function reset_interval() {
if (timer != 0) {
clearInterval(timer);
timer = 0;
timer = setInterval("auto_logout()", 300000);
}
}
function auto_logout() {
window.location = "<?php echo base_url('staff/staff_logout'); ?>";
}
As for the logging out when browser closes that also has been taken care in the config.php file by doing $config['sess_expiration'] = 0;
But now I want to do it when a tab is closed so I tried the following code:-
var unloadEvent = function (e) {
var confirmationMessage = "Warning: Leaving this page will result in any unsaved data being lost. Are you sure you wish to continue?";
return confirmationMessage;
};
window.addEventListener("beforeunload", unloadEvent);
But it's not working. I'm using Chrome 71.0.3578.98. Any help will be appreciated. thanks in advance.

How can i refresh after 10 seconds when alert box shows up?

So ive been trying to make automatic logout, but i cannot find a way to logout after like 10secs after the alertbox (alertbox asks if you wanna logout if you havent still left the site but are browsing for some information and dont wanna log out) shows up automatically. Basically i wanna make it automatically logout if you dont press anything on the alertbox after chosen time like 10secs.
Heres the code!
var refresh_rate = 5; // <-- In seconds, change to your needs
var reset_rate = 7; // <-- In seconds logs out after not pressing OK or cancel in automatic logout
var last_user_action = 0;
var has_focus = false;
var lost_focus_count = 0;
var focus_margin = 10; // If we lose focus more then the margin we want to refresh
function reset() {
last_user_action = 0;
console.log("Reset");
}
function windowHasFocus() {
has_focus = true;
}
function windowLostFocus() {
has_focus = false;
lost_focus_count++;
console.log(lost_focus_count + " <~ Lost Focus");
}
setInterval(function () {
last_user_action++;
refreshCheck();
}, 1000);
function refreshCheck() {
var focus = window.onfocus;
if ((last_user_action >= refresh_rate && !has_focus && document.readyState == "complete") || lost_focus_count > focus_margin) {
var answer = confirm("Session About To Timeout\n\n You will be automatically logged out.\n Confirm to remain logged in.")
if (answer){
refresh_rate = 10;
}
else{
window.location.reload(); // If this is called no reset is needed
reset(); // We want to reset just to make sure the location reload is not called.
}
}
}
I hope someone can help me with this problem!
You can't, if you use confirm (or alert or prompt, any of those relics of the 1990s). They bring the main JavaScript thread to a screeching halt (mostly, there's nuance around this now), meaning you can't do anything else (mostly).
To do this, you need to replace the confirm with a DOM element showing the message instead, which won't block the main JavaScript thread.

If Deeplink url not work send user to download page

I need to implement a javascript where I can detect if my deep link is worked or not, If it works then it should remain same but if it does not work then it must start download file.
For that, i use timeout function to do it. Here is sample code I used.
setTimeout(function () { window.location = "https://itunes.apple.com/appdir"; }, 25);
window.location = "appname://";
But this code works fine on android and ios but it is creating problem while it comes to the desktop browser. In desktop browser after Deeplink works properly, timeout function do not stops and it redirects to download page.
so finally I want some event which can detect if my Deeplink is worked or not so I can set cleartimeout function to prevent redirecting to downloading URL
I have been facing similar problem, and finally I have found a nice botched job to make it work:
var timer = null;
function setListener() {
window.document.addEventListener("visibilitychange", function(e) {
window.clearTimeout(timer);
timer = null;
window.open('','_self').close();
});
}
function redirectAndroid() {
setTimeout(function () { window.location = "https://itunes.apple.com/appdir"; }, 25);
window.location = "appname://";
}
function redirecIOS() {
setListener();
var beforeApp = new Date().valueOf();
window.location.href = "appname://";
var afterApp = new Date().valueOf();
if (afterApp - beforeApp < 100) {
setTimeout(function() {
"https://itunes.apple.com/appdir";
}, 25);
} else {
if (timer === null) {
timer = setTimeout(function() {
"https://itunes.apple.com/appdir";
}, 200);
}
}
This way, after redirecting to application, if it opens it triggers the event "visibilitychange" before the timeout function, and you clear the timeout avoiding it to redirect to web, and close the browser (if you want). If application is not installed, timeAfterApp - timeBeforeApp is not < 100 so there you set the timeout.
For desktop browser, consider using window blur listener and act accordingly
Blur listener will tell you if user left the tab or browser
window.onblur=()=>{//deeplink check (maybe unsuccessfull?)
window.onfocus=()=>{//deeplink unsucesfull};
}
I would try with a timestamp expression in the timeout.
Something like this (play around with the thresholds as needed):
var clickedTm = +new date;
setTimeout(function () {
if (+new date - clickedTm < 600) {
window.location = "https://itunes.apple.com/appdir";
}
}, 500);
window.location = "appname://";

Detect connection issues in iframe

this questions is related to an html file calling out different pages in different iframe tags. Is there a way, using JavaScript probably, to check if there was a connection issue to the page? If so, to try reloading this frame until the connection is established.
To be a bit clearer, if you have a look at the following link (http://tvgl.barzalou.com) (even if the content is in French, you will notice how different parts of the page load, and more often than not, loads correctly). But once in a while, during the weekend, a slight connection issue to the net arrives and for some reason, the frame gives out this ridiculous grey / light grey icon saying that there was a connection issue. Of course, when the page is manually reloaded, the frame comes back to life.
Please check the updated code that will check and reload the iframe after the max attempts have been reached...
<script language="javascript">
var attempts = 0;
var maxattempt = 10;
var intid=0;
$(function()
{
intid = setInterval(function()
{
$("iframe").each(function()
{
if(iframeHasContent($(this)))
{
//iframe has been successfully loaded
}
if(attempts < maxattempt)
{
attempts++;
}
else
{
clearInterval(intid);
checkAndReloadIFrames();
}
})
},1000);
})
function iframeHasContent($iframe)
{
if($iframe.contents().find("html body").children() > 0)
{
return true;
}
return false;
}
function checkAndReloadIFrames()
{
$("iframe").each(function()
{
//If the iframe is not loaded, reload the iframe by reapplying the current src attribute
if(!iframeHasContent($(this)))
{
//reload iframes if not loaded
var $iframe = $(this);
var src = $iframe.attr("src");
//code to prevent cache request and reload url
src += "?_" + new Date().getTime();
$iframe.attr("src",src);
}
});
}
</script>
You can schedule a code which will check whether the iframes are loaded properly or not
Consider a sample
<script language="javascript">
var attempts = 0;
var maxattempt = 10;
var intid=0;
$(function()
{
intid = setInterval(function()
{
$("iframe").each(function()
{
if(iframeHasContent($(this)))
{
//iframe has been successfully loaded
}
if(attempts < maxattempt)
{
attempts++;
}
else
{
clearInterval(intid);
}
})
},1000);
})
function iframeHasContent($iframe)
{
if($iframe.contents().find("html body").children() > 0)
{
return true;
}
return false;
}
</script>
This simple code snippet will check whether iframes in the document have been loaded properly or not. It will try this for 10 attempts then it will abort the checking.
When the checking is aborted, you can call iframeHasContent() for each iframe to shortlist the ones that have not been loaded and reload them if required.

how to keep the session active even i opened in multiple tabs in same browser

i would like to implement one thing.i opened my site in multiple tabs. while i work in one tab others tabs should not be timedout. it should be alive. how to keep alive for other tabs. i used below js to find idle time logout.
<script type="text/javascript">
idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval("timerIncrement()", 60000); // 1 minute
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
})
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 2) { // 30 minutes
var beforeTime = new Date()
var bminutes = beforeTime.getMinutes();
var bseconds = beforeTime.getSeconds();
var user='<?php echo Auth::getSessionUserFullName();?>';
if(user!='')
{
var timehours=beforeTime.getHours();
var timeoutmin=bminutes+1;
var timeoutseconds=bseconds-1;
if(timeoutseconds>59)
{
timeoutseconds=0;
timeoutmin=timeoutmin+1;
}
if(timeoutmin>59)
{
timeoutmin=0;
timehours=hours+1;
}
if(timehours>24)
{
timehours=0;
}
var ok=confirm("Your session expire time started at "+beforeTime.getHours()+":"+beforeTime.getMinutes()+":"+beforeTime.getSeconds()+".Please click 'OK' before "+timehours+":"+timeoutmin+":"+timeoutseconds+" to stay signed in.");
if(ok)
{
var currentTime = new Date()
var aminutes = currentTime.getMinutes();
var aseconds = currentTime.getSeconds();
var time=aminutes-bminutes;
if(aminutes>bminutes && aseconds>bseconds)
{
alert('Time out!!Please login again to access.');
window.location.href='<? echo APPLICATION_WEBROOT?>auth/logout';
return false;
}
else if(time>=2)
{
alert('Time out!!Please login again to access.');
window.location.href='<? echo APPLICATION_WEBROOT?>auth/logout';
return false;
}
else
{
return true;
}
}
else
{
window.location.href='<? echo APPLICATION_WEBROOT?>auth/logout';
}
}
}
}
</script>
Please help me. how to keep the sessions for all opened tabs.thanks in advance
The session is not tab specific. It is for the whole browser instance.
The session is extended when a user makes a request to the server. So depending on your application, you may have to generate regular requests to the server to extend that session.
For that, you can use the setInterval javascript function to trigger an AJAX call to your PHP backend.
Hope that helps...
BTW: be careful because some browsers do deactivate the tabs which don't have the user focus (Chrome for example) - it will not modify session... but some JS could be suspended.
One of the way I can think of is handle the session yourself in the server.
Here's a system that might work (welcome suggestions of improvement):
1) store your own custom session in server DB, with IP being the unique identifier.
2) whenever user interacts with your server, grab its IP and update the corresponding session stored in server. If that session has already timeout, redirect user to timeout page.
there might be many things that I haven't though through, but in my mind this should be a viable way to maintain session across tabs

Categories