Repeating/looping javascript function to check if a cookie has changed - javascript

I am trying to make a script that will repeat every 5 seconds.
The script that will be repeated will check to see if a cookie exists.
If the cookie does not exist, the page is redirected.
If the cookie does exist, nothing happens.
The cookies are working fine, my only problem is that it doesn't repeat!
I am using jQuery to identify/check the cookie and that is working fine.
I would like to know what is wrong with the code please.
I have looked online many times, but have had no luck in finding what I need.
This is the cookie plugin I use: https://github.com/carhartl/jquery-cookie
var checkcookie = $.cookie('myCookie');
checklogin();
function checklogin(){
setTimeout(function(){
if(checkcookie == null){
//if cookie not set
window.location.href='/';
}
else{
//if cookie set
}
}, 5000);
checklogin();//to recall the script after it is done
}
Or if any one has an alternative method of checking whether a cookie has changed, I would love to know!

It's working fine, but your cookie value not changing - it set once and forever. Try to include it in your setTimeout():
checklogin();
function checklogin(){
setTimeout(function(){
var checkcookie = $.cookie('myCookie');
if(checkcookie == null){
window.location.href='/';
}
else{
//if cookie set
}
}, 5000);
checklogin(); //to recall the script after it is done
}

If you're doing it that way the checklogin call has to be inside the setTimeout function otherwise it's called immediately everytime.
Also i'd use a setInterval instead, so you don't need you recursive function:
setInterval(function(){
if(checkcookie == null){
window.location.href='/';
}else{
//if cookie set
}
},5000);

Related

How to automatically reload a web page

I want my website page to reload once when it has already opened for the first time. I wrote this function in my javascript file for that...
var i;
$(document).ready(function(){
for ( i=0;i<1;i++){
if(i===0){
location.reload();
break;
}
}
});
But the page keeps reloading again and again as if the above function was a recursive one.
How do I do this?
P.S I'm doing it because of this issue.
<script type='text/javascript'>
(function() {
if( window.localStorage ) {
if( !localStorage.getItem('firstLoad') ) {
localStorage['firstLoad'] = true;
window.location.reload();
} else
localStorage.removeItem('firstLoad');
}
})();
</script>
Here is what's happening:
The page loads for the first time, jQuery calls any handlers on the document.ready event
The page reloads
The document.ready call is made again
repeat
Out of curiosity, why would you want to do that? And why do you have a for loop that will run for one iteration?
Also, to answer your question as far as I know the only way to make sure the page doesn't reload is use a cookie that lasts for about 5 seconds. Then, on document.ready check for that cookie and if it exists then don't reload.
You must either set a cookie (or use javascript's localStorage), or use xhr to retrieve a value held on a remote server.
If you want to use cookies, it's as simple as
document.cookie = "username=John Doe";
where the document.cookie is a query string of the form (x=y;a=b;n=z)
If you want the page to reload every time the user vists, be sure to unset the cookie once you've done any necessary processing when a page reload has been set.
$( window ).load(function() {
if (window.location.href.indexOf('reload')==-1) {
window.location.replace(window.location.href+'?reload');
}
});
Code is ok. But if the page is opened from another page with a link to an id (.../page.html#aa) the code only works with firefox. With other browsers reload the page without going to id. (Sorry for my english).
I found the solution with this code. It is assumed that the page is refreshed no earlier than one hour. Otherwise, add minutes to the oggindex variable.
<script>
var pagina = window.location.href;
var d = new Date();
var oggiindex = d.getMonth().toString()+'-'+d.getDate().toString()+'-'+d.getHours().toString();
if (localStorage.ieriindex != oggiindex)
{
localStorage.setItem("ieriindex", oggiindex);
window.location.replace(pagina);
}
</script>
Yours code executed each time $(document).ready(), so it's not surprise that your loop is infinity - each load finished as ready state.
If you give more detailed requirements we can solve it with no using window object as data holder. It's bad way but you can set it for test.
Window object stores variables not depend on reload because it's higher then document.
Let's try:
if( window.firstLoad == undefined ){
// yours code without any loop
// plus:
window.firstLoad = false;
}
You can make it with localStorage API.
Check this link also, it's giving more information about window object variables:
Storing a variable in the JavaScript 'window' object is a proper way to use that object?

retain a JQuery Variable value over multiple postbacks

I want to have a boolean variable to retain its value even if the Page reloads in Jquery. Here is what I am doing.
var TimedOut = false;
alert("Time Out Value = " + TimedOut);
if (!TimedOut) {
//do some Processing and stay on same Page
Timedout = true;
// redirect to current Page using window.location.href on session timeout
}
The Value of Timedout which I am setting it in the loop is always false, and if statement is always true. I want it to load only once for false and once set to true it should retain the value. I am using this to decide if we need to redirect to home page or not.
Not sure if I can do this via JQuery.
try to use a cookie this library could do the trick, https://github.com/js-cookie/js-cookie
Cookies.set('timeout', 'false');
var timeout = Cookies.get('timeout');
alert("Time Out Value = " + TimedOut);
if (!TimedOut) {
//do some Processing and stay on same Page
Cookies.set('timeout', 'true');
// redirect to current Page using window.location.href on session timeout
}
I just replace your code and added the cookie functionality but you know better the logic.
I hope that helps.
You could persist that value in localStorage:
localStorage.setItem('Timedout', true);
and
localStorage.getItem('Timedout');
Yes, you can do this via jQuery with a cookie as jack wrote or WebStorage API (localStorage or sessionStorage) which is for new browsers only with HTML5 support.

Removing the setTimeout interval

After loading the document, I want to refresh the page once. So I wrote this code. It is working fine, but it is calling again and again. because I am refreshing same page. but I want to clear the interval after one time execution.
function refreshPage(){
document.location.reload(true);
alert('page is refresh.');
}
var interval = setTimeout('refreshPage()', 3000);
If you want it to work only once, whatever the delay, you could store in localStorage the fact you did it :
function refreshPage(){
alert('page will refresh.');
document.location.reload(true);
localStorage['refreshDone'] = 'yes';
}
if (!localStorage['refreshDone']) {
setTimeout('refreshPage()', 3000);
}
But you can't simply clear the timeout or interval as the window variables are lost each time you reload the page.
As I'm not sure of your exact goal, in case you'd want to refresh if it hasn't been done recently, you could store a timestamp in localStorage :
function refreshPage(){
alert('page will refresh.');
document.location.reload(true);
localStorage['refresh'] = new Date().getTime();
}
var lastTimeRefresh = parseInt(localStorage['refresh']||'0', 10);
if (new Date().getTime() - lastTimeRefresh > 30*60*1000) { // 30 minutes
setTimeout('refreshPage()', 3000);
}
You could set javascript cookies at the first refresh and then check if cookies are set or not, If it is not set please set the cookies and refresh the page, If not do nothing

Check if window.history.go successful?

Is there anyway to check if a window.history.go command is successful in changing the window.location or not?
i.e. If I do a window.history.go(-5) when there are only 3 pages in the history stack, the browser will do nothing.
Is there a way to check if that happens and run other code? An error callback, of sorts.
Thanks.
For an immediate response, first you'll want to check history.length to make sure it is at least 6, e.g. to go -5. Apart from that, I think the only way is to use setTimeout and if the script is still running, the callback will be executed.
Not really a JS expert, but if you want to perform some action when the user goes back or forward, you could use URL hashes and trigger some function using the jQuery onhashchange event. This will not give you the position in history, and i'm also not sure about cross-browser compatibility, but it did the job for me so far.
$(window).on('load' function(){
var hash = parent.top.location.hash;
if(hash == '' || hash == '#' || hash == null){
//if none, set a hash and reload page
parent.top.location.hash = '#/some/hash';
parent.top.location.reload(true);//use true if you dont want to use cached items
}
});
$(window).on('hashchange', function(){
do_something(parent.top.location.hash);
});
function do_something(hash){
//this function will be executed each time the '#' changes
console.log('hash changed to '+hash);
}

Global variable isn't holding?

This should be a really easy "derp" question, but here it is:
I'm trying to set up a global variable in a JS file so that I can control when an action triggers. In my case, I want okBoxCall to only be called if firstTime is true. I have firstTime set to true initially, then I change it to false afterwards. My code is NOT working as it should however, as it still calls up okBoxCall more than once.
var Dialog;
var HUDWindow;
var smartPhone;
var firstTime = true;
$(document).ready(function(){
smartPhone = new SmartPhone();
initDialog();
initHUDWindow();
if(firstTime == true)
{
okBoxCall("Tutorial", "Welcome to McLarin Energy!");
firstTime = false;
}
});
What am I doing wrong? Obviously firstTime is not holding its change to false...
EDIT Forgot to mention that this is for a 3D game, not web pages. Cookies are not used.
I'm guessing you want to check whether this is the first time the user opens a page and open a tutorial if it is?
It is not possible the way you want to do it. Every time your page is loaded your script is evaluated again. So this means a variable firstTime is created and it is set to true. What you need is some persistent storage on the client to store whether it is the first time or not. You will need to set a cookie or call the localStorage API if you don't bother disregarding older browsers.
Your function should only be called once due to $(document).ready(...). So, I'm guessing you're reloading the page to get the alert to display again and again...
Maybe you should be looking at using cookies, not just a plain old JS variable..?
What is okBoxCall doing? If you have any error in okBoxCall firstTime = false will not be executed. Set the value before you call okBoxCall.
$(document).ready(function(){
smartPhone = new SmartPhone();
initDialog();
initHUDWindow();
if(firstTime == true)
{
firstTime = false;
okBoxCall("Tutorial", "Welcome to McLarin Energy!");
}
});

Categories

Resources