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

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.

Related

JavaScript ignore alert if reloading page

I am detecting the end of a webrtc stream in JavaScript like this...
stream.getVideoTracks()[0].onended = () => {
alert('Feed Has Ended');
};
This is working correctly, but if the user refreshes or reloads the page then the alert is also shown.
I understand that this is technically correct, but how can I get it to not display the alert under those conditions?
Why don't you use a global boolean to check if video is playing or not? When you will reload or refresh the page, isVideoRunning will become false and alert won't show.
Like
this.isVideoRunning = false;
On addtrack,
this.rtcPeerCon_.ontrack = function (event) {
if (!this.rtcPeerCon_) {
return;
}
if( !this.remoteVideo_ ) {
return;
}
this.remoteVideo_.srcObject = event.streams[0];
this.isVideoRunning = true;
}
then in your onStream ended callback you can check
if (this.isVideoRunning) {
alert('whatever');
this.isVideoRunning = false;
}
(I wanted this to be comment but I am not allowed to comment yet)

function always ignore the first argument?

I have a content that will show when we scroll.
when the content show, user can close it. If user choose to close it and then refresh the page. Even user scroll up the page, the content will not show up until 10 minutes.
heres my code:
var popUp= document.getElementById("popup");
var closePopUp= document.getElementsByClassName('popup-close');
var halfScreen= document.body.offsetHeight/2;
var showOnce = true;
var delay;
function slideUp(){
popUp.style.maxHeight="400px";
popUp.style.padding="10px 20px";
popUp.style.opacity="1";
if(popUp.className==="closed"){
popUp.className="";
}
}
function slideDown(){
popUp.style.maxHeight="0";
popUp.style.padding="0 20px";
popUp.style.opacity="0";
// add class closed for cache
if(popUp.className===""){
popUp.className="closed";
localStorage.setItem('closed', 'true'); //store state in localStorage
}
}
I set the interval for user that close the content than refresh the page
// start interval
function startDelay() {
delay = setInterval(slideUp, 1000);
}
// clear interval
function clearDelay() {
window.clearTimeout(delay);
}
// check if cache heve class close
window.onload = function() {
var closed = localStorage.getItem('closed');
if(closed === 'true'){
popUp.className="closed";
}
}
here, I put 2 arguments for first time visit and multiple time
// show popup when scroll 50%
window.onscroll = function scroll(ev) {
// first time visited
if ((popUp.className==="closed" && window.innerHeight+window.scrollY) >= halfScreen && showOnce){
startDelay();
showOnce = false;
}
// same user multiple time visited the site
else if((popUp.className==="" && window.innerHeight+window.scrollY) >= halfScreen && showOnce){
slideUp();
showOnce = false;
}
};
// close button when click close
for(var i = 0; i<closePopUp.length; i++){
closePopUp[i].addEventListener('click', function(event) {
slideDown();
});
}
when I first time open the page, the content show up, and it gets closed class when I choose to close the content (it's correct). But after I scroll to top refresh the page, its show with interval (correct too).
problem:
1. if i refresh not on top of page, the content will show immediatly.
2. after i refresh and scroll and close the content. the content show again.
its like it read the function again? please help

Checking if a page is up prior to loading the page

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.

Javascript onUnload Show offer and redirect to offer page if stays on page [duplicate]

Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.

need to set a timer for in javascript , then clear

I want to create a timer in JavaScript. I see the setTimeout(fn, 100) but unclear how to wrap this so it will clear itself at the end.
I tried doing
var buttonTimer = null;
$scope.backButton = function() {
if(buttonTimer === null){
$history.back();
}
buttonTimer = setTimeout(function(buttonTimer){
buttonTimer = null;
}, 100);
}
The whole point is to prevent the user from hitting this function too quickly.. and ignoring all subsequent clicks within that 100ms window, at the end of the window, clear the timer and resume accepting clicks
Since you are doing angular, I prepared a plnkr for demonstration:
http://plnkr.co/edit/5qrslKpmkglXTvEyYgBr?p=preview
Your code is almost Ok, the only problem is that you start a new timeout on every click. The effect is, that the callback fires multiple times and resets buttonTimer.
So the only change is:
var blocker = null;
$scope.backButton = function() {
if(blocker == null) {
blocker = setTimeout(function(){
blocker = null;
}, 1500);
// DO YOUR STUFF HERE
}
};
You can use throttle from lodash/underscore or Ramdajs.
for example
$scope.backButton=_.throttle(100,function(){/* do something here */});

Categories