How to automatically reload a web page - javascript

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?

Related

How can I create a dynamic product page using HTML, CSS, and Javascript

I currently only know javascript. But the thing is I looked up how to do it and some people talk about something called localStorage. I have tried this and for some reason when I jump to a new page those variables aren't kept. Maybe I am doing something wrong? I jump to a new page via
and all I want do do is select a certain image. take that image to a new page and add it to that page.
I tried using the localStorage variables and even turning it into JSON.stringify and doing JSON.parse when trying to call the localstorage to another script. It didn't seem to work for me. Is there another solution?
This is some of my code. There are two scripts.
document.querySelectorAll(".card").forEach(item => {
item.addEventListener("click", onProductClick);
})
var div;
var productImg;
var ratingElement;
var reviewCount;
var price;
function onProductClick(){
// This took a week to find out (this.id)
// console.log(this.id);
div = document.getElementById(this.id);
productImg = div.getElementsByTagName('img')[0];
ratingElement = div.getElementsByTagName('a')[2];
reviewCount = div.getElementsByTagName('a')[3]
price = div.getElementsByTagName('a')[4];
console.log(div.getElementsByTagName('a')[4]);
var productData = [div, productImg,ratingElement,reviewCount,price];
window.localStorage.setItem("price", JSON.stringify(price));
}
function TranslateProduct(){
console.log("Hello");
}
This is script 2
var productPageImage = document.getElementById("product-image");
var myData = localStorage['productdata-local'];
var value =JSON.parse(window.localStorage.getItem('price'));
console.log(value);
// function setProductPage(img){
// if(productImg != null){
// return;
// }
// console.log(window.price);
// }
To explain my thought process on this code in the first script I have multiple images that have event listeners for a click. I wanted to Click any given image and grab all the data about it and the product. Then I wanted to move that to another script (script 2) and add it to a dynamic second page. yet I print my variables and they work on the first script and somehow don't on the second. This is my code. in the meantime I will look into cookies Thank you!
Have you tried Cookies
You can always use cookies, but you may run into their limitations. These days, cookies are not the best choice, even though they have the ability to preserve data even longer than the current window session.
or you can make a GET request to the other page by attaching your serialized object to the URL as follows:
http://www.app.com/second.xyz?MyObject=SerializedData
That other page can then easily parse its URL and deserialize data using JavaScript.
you can check this answer for more details Pass javascript object from one page to other

How to reload page when jquery.counter trigger finish.countdown event for multiple instance?

I am using multiple instance for jQuery countdown and implement page reload when counter get finished
E.g.
$('.countdown').each(function() {
var $this = $(this),
finalDate = $(this).data('countdown');
$this.countdown((finalDate), function(event) {
var days = event.strftime('%D');
$(this).find('.days').children('span').html(days);
$(this).find('.hours').children('span').html(event.strftime('%H'));
$(this).find('.minutes').children('span').html(event.strftime('%M'));
$(this).find('.seconds').children('span').html(event.strftime('%S'));
});
$(this).on('finish.countdown', function(event){
/*if(!window.location.hash && !(window.location.hash.indexOf('_loaded') > -1)) {
window.location = window.location + '#_loaded'; window.location.reload();
}*/
//If I put window location reload here it will goes into infinite loop. Also above commented code will reload page twice initially which is also not valid solution.
});
});
Issue: If countdown is already finished (E.g. 00:00:00:00 ) then page reload occur twice when script loaded at first time,
I have used localStorage concept but unable to find exact solution. Please help
I had almost this issue with page constantly reloading instantly.
Try and check if your local time and server time are the same. In my case, the difference was two hours, which was the issue that put the page into constant loop.
Countdown plugin has some notes on timezone awareness: http://hilios.github.io/jQuery.countdown/examples/timezone-aware.html

How to delete a localStorage item when the browser window/tab is closed?

My Case: localStorage with key + value that should be deleted when browser is closed and not single tab.
Please see my code if its proper and what can be improved:
//create localStorage key + value if not exist
if (localStorage) {
localStorage.myPageDataArr = {
"name" => "Dan",
"lastname" => "Bonny"
};
}
//when browser closed - psedocode
$(window).unload(function() {
localStorage.myPageDataArr = undefined;
});
should be done like that and not with delete operator:
localStorage.removeItem(key);
Use with window global keyword:-
window.localStorage.removeItem('keyName');
You should use the sessionStorage instead if you want the key to be deleted when the browser close.
You can make use of the beforeunload event in JavaScript.
Using vanilla JavaScript you could do something like:
window.onbeforeunload = function() {
localStorage.removeItem(key);
return '';
};
That will delete the key before the browser window/tab is closed and prompts you to confirm the close window/tab action. I hope that solves your problem.
NOTE: The onbeforeunload method should return a string.
localStorage.removeItem(key); //item
localStorage.clear(); //all items
There is a very specific use case in which any suggestion to use sessionStorage instead of localStorage does not really help.
The use-case would be something as simple as having something stored while you have at least one tab opened, but invalidate it if you close the last tab remaining.
If you need your values to be saved cross-tab and window, sessionStorage does not help you unless you complicate your life with listeners, like I have tried.
In the meantime localStorage would be perfect for this, but it does the job 'too well', since your data will be waiting there even after a restart of the browser.
I ended up using a custom code and logic that takes advantage of both.
I'd rather explain then give code. First store what you need to in localStorage, then also in localStorage create a counter that will contain the number of tabs that you have opened.
This will be increased every time the page loads and decreased every time the page unloads. You can have your pick here of the events to use, I'd suggest 'load' and 'unload'.
At the time you unload, you need to do the cleanup tasks that you'd like to when the counter reaches 0, meaning you're closing the last tab.
Here comes the tricky part: I haven't found a reliable and generic way to tell the difference between a page reload or navigation inside the page and the closing of the tab.
So If the data you store is not something that you can rebuild on load after checking that this is your first tab, then you cannot remove it at every refresh.
Instead you need to store a flag in sessionStorage at every load before increasing the tab counter.
Before storing this value, you can make a check to see if it already has a value and if it doesn't,
this means you're loading into this session for the first time, meaning that you can do the cleanup at load if this value is not set and the counter is 0.
use sessionStorage
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window.
The following example counts the number of times a user has clicked a button, in the current session:
Example
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
Try using
$(window).unload(function(){
localStorage.clear();
});
Hope this works for you
There are five methods to choose from:
setItem(): Add key and value to localStorage
getItem(): Retrieve a value by the key from localStorage
removeItem(): Remove an item by key from localStorage
clear(): Clear all localStorage
key(): Passed a number to retrieve nth key of a localStorage
You can use clear(), this method when invoked clears the entire storage of all records for that domain. It does not receive any parameters.
window.localStorage.clear();
for (let i = 0; i < localStorage.length; i++) {
if (localStorage.key(i).indexOf('the-name-to-delete') > -1) {
arr.push(localStorage.key(i));
}
}
for (let i = 0; i < arr.length; i++) {
localStorage.removeItem(arr[i]);
}
8.5 years in and the original question was never actually answered.
when browser is closed and not single tab.
This basic code snippet will give you the best of both worlds. Storage that persists only as long as the browser session (like sessionStorage), but is also shareable between tabs (localStorage).
It does this purely through localStorage.
function cleanup(){
// place whatever cleanup logic you want here, for example:
// window.localStorage.removeItem('my-item')
}
function tabOpened(){
const tabs = JSON.parse(window.localStorage.getItem('tabs'))
if (tabs === null) {
window.localStorage.setItem('tabs', 1)
} else {
window.localStorage.setItem('tabs', ++tabs)
}
}
function tabClosed(){
const tabs = JSON.parse(window.localStorage.getItem('tabs'))
if (tabs === 1) {
// last tab closed, perform cleanup.
window.localStorage.removeItem('tabs')
cleanup()
} else {
window.localStorage.setItem('tabs', --tabs)
}
}
window.onload = function () {
tabOpened();
}
window.onbeforeunload = function () {
tabClosed();
}
why not used sessionStorage?
"The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window."
http://www.w3schools.com/html/html5_webstorage.asp
Although, some users already answered this question already, I am giving an example of application settings to solve this problem.
I had the same issue. I am using https://github.com/grevory/angular-local-storage module in my angularjs application. If you configure your app as follows, it will save variable in session storage instead of local storage. Therefore, if you close the browser or close the tab, session storage will be removed automatically. You do not need to do anything.
app.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('myApp')
.setStorageType('sessionStorage')
});
Hope it will help.
Here's a simple test to see if you have browser support when working with local storage:
if(typeof(Storage)!=="undefined") {
console.log("localStorage and sessionStorage support!");
console.log("About to save:");
console.log(localStorage);
localStorage["somekey"] = 'hello';
console.log("Key saved:");
console.log(localStorage);
localStorage.removeItem("somekey"); //<--- key deleted here
console.log("key deleted:");
console.log(localStorage);
console.log("DONE ===");
} else {
console.log("Sorry! No web storage support..");
}
It worked for me as expected (I use Google Chrome).
Adapted from: http://www.w3schools.com/html/html5_webstorage.asp.
I don't think the solution presented here is 100% correct because window.onbeforeunload event is called not only when browser/Tab is closed(WHICH IS REQUIRED), but also on all other several events. (WHICH MIGHT NOT BE REQUIRED)
See this link for more information on list of events that can fire window.onbeforeunload:-
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
After looking at this question 6 years after it was asked, I found that there still is no sufficient answer to this question; which should achieve all of the following:
Clear Local Storage after closing the browser (or all tabs of the domain)
Preserve Local Storage across tabs, if at least one tab remains active
Preserve Local Storage when reloading a single tab
Execute this piece of javascript at the start of each page load in order to achieve the above:
((nm,tm) => {
const
l = localStorage,
s = sessionStorage,
tabid = s.getItem(tm) || (newid => s.setItem(tm, newid) || newid)((Math.random() * 1e8).toFixed()),
update = set => {
let cur = JSON.parse(l.getItem(nm) || '{}');
if (set && typeof cur[tabid] == 'undefined' && !Object.values(cur).reduce((a, b) => a + b, 0)) {
l.clear();
cur = {};
}
cur[tabid] = set;
l.setItem(nm, JSON.stringify(cur));
};
update(1);
window.onbeforeunload = () => update(0);
})('tabs','tabid');
Edit: The basic idea here is the following:
When starting from scratch, the session storage is assigned a random id in a key called tabid
The local storage is then set with a key called tabs containing a object those key tabid is set to 1.
When the tab is unloaded, the local storage's tabs is updated to an object containing tabid set to 0.
If the tab is reloaded, it's first unloaded, and resumed. Since the session storage's key tabid exists, and so does the local storage tabs key with a sub-key of tabid the local storage is not cleared.
When the browser is unloaded, all session storage will be cleared. When resuming the session storage tabid won't exists anymore and a new tabid will be generated. Since the local storage does not have a sub-key for this tabid, nor any other tabid (all session were closed), it's cleared.
Upon a new created tab, a new tabid is generated in session storage, but since at least one tabs[tabid] exists, the local storage is not cleared
This will do the trick for objects.
localStorage.removeItem('key');
Or
localStorage.setItem('key', 0 );
You can simply use sessionStorage. Because sessionStorage allow to clear all key value when browser window will be closed .
See there : SessionStorage- MDN
This is an old question, but it seems none of the answer above are perfect.
In the case you want to store authentication or any sensitive information that are destructed only when the browser is closed, you can rely on sessionStorage and localStorage for cross-tab message passing.
Basically, the idea is:
You bootstrap from no previous tab opened, thus both your localStorage and sessionStorage are empty (if not, you can clear the localStorage). You'll have to register a message event listener on the localStorage.
The user authenticate/create a sensitive info on this tab (or any other tab opened on your domain).
You update the sessionStorage to store the sensitive information, and use the localStorage to store this information, then delete it (you don't care about timing here, since the event was queued when the data changed). Any other tab opened at that time will be called back on the message event, and will update their sessionStorage with the sensitive information.
If the user open a new tab on your domain, its sessionStorage will be empty. The code will have to set a key in the localStorage (for exemple: req). Any(all) other tab will be called back in the message event, see that key, and can answer with the sensitive information from their sessionStorage (like in 3), if they have such.
Please notice that this scheme does not depend on window.onbeforeunload event which is fragile (since the browser can be closed/crashed without these events being fired). Also, the time the sensitive information is stored on the localStorage is very small (since you rely on transcients change detection for cross tab message event) so it's unlikely that such sensitive information leaks on the user's hard drive.
Here's a demo of this concept: http://jsfiddle.net/oypdwxz7/2/
There are no such the way to detect browser close so probably you can't delete localStorage on browser close but there are another way to handle the things you can uses sessionCookies as it will destroy after browser close.This is I implemented in my project.
if(localStorage.getItem("visit") === null) {
localStorage.setItem('visit', window.location.hostname);
console.log(localStorage.getItem('visit'));
}
else if(localStorage.getItem('visit') == 'localhost'){
console.log(localStorage.getItem('visit'));
}
else {
console.log(localStorage.getItem('visit'));
}
$(document).ready(function(){
$("#clickme").click(function(){
localStorage.setItem('visit', '0');
});
});
window.localStorage.removeItem('visit');
window.addEventListener('beforeunload', (event) => {
localStorage.setItem("new_qus_id", $('.responseId').attr('id'));
var new_qus_no = localStorage.getItem('new_qus_id');
console.log(new_qus_no);
});
if (localStorage.getItem('new_qus_id') != '') {
var question_id = localStorage.getItem('new_qus_id');
} else {
var question_id = "<?php echo $question_id ; ?>";
}
you can try following code to delete local storage:
delete localStorage.myPageDataArr;

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