javascript testing variables for setting cookies - javascript

i am getting nuts with something .
What i am trying to do is to set a cookie when loading a certain page so that when being on another page and the cookies has been set, the page is refreshed.
My condition tests do not react as how i expect it .
here is where i am at :
$( window ).load(function() {
var page=$(".listing_voyage");
//alert('page:'+page.length);
//alert('cookie:'+getCookie('refresh'));
if (getCookie('refresh') && page.length )
{
window.location.reload(true);
SetCookie("refresh",false);
alert('i am reloading');
}
});
var page_produit=$("#page_produit");
if (page_produit.length)
{
SetCookie("refresh",true);
}

Once you reload the page, the javascript is lost, and everything starts over
window.location.reload(true); // reloads page
SetCookie("refresh",false); // and this is not executed, as the page reloaded
alert('i am reloading');
You'll have to set the cookie before reloading
SetCookie("refresh",false);
window.location.reload(true);
But why exactly are you reloading the page to begin with, it seems like a strange thing to do ?

Related

Is it possible to add a javascript for/while loop for location.reload();

My Wordpress site has conflicting plugins. So when I click a page in the menu, it get stuck but fixes when the page has been re-loaded.
My approach is to auto refresh the page (the menu link that has been clicked) so the page will properly load.
After searching for couple of days, I haven't found the exact way to do it.
I use
location.reload(true);
but it keeps reloading. I tried also
location.reload(true);
window.stop();
but it stops loading before it completes the page load to 100%.
So my question is, can we add a loop to stop the reload?
example…
after 2 reloads, the js code will stop
Hopefully someone can help me. Thanks!
Try this piece of JavaScript, it stores the reload count in LocalStorage:
if(typeof(localStorage.getItem('rlcount')) == 'undefined'){
localStorage.setItem('rlcount', 0);
}
if(localStorage.getItem('rlcount') < 2){
localStorage.setItem('rlcount', localStorage.getItem('rlcount') + 1);
window.location.reload();
}else{
localStorage.removeItem('rlcount');
}
However, you should note that reloading a page is not a good fix for your bug, you should find the root cause.
While I would encourage you to try to fix the root problem causing the behavior you described, you could do something like the following to reload the page twice:
window.onload = function() {
if (!window.location.hash) {
window.location = window.location + '#loadedOnce';
alert("Reloading first time...");
window.location.reload();
} else if (window.location.hash === "#loadedOnce") {
window.location = window.location.hash.replace("#loadedOnce", "#loadedTwice");
alert("Reloading second time...");
window.location.reload();
} else if (window.location.hash === "#loadedTwice") {
// Page reloaded twice, do whatever...
}
}
This makes use of a hash in the URL, so it does not require using the localStorage API (although that is a perfectly fine approach too if the browser supports it, and might work better if you already have hashes in the URL).
Thank you for taking time to answer my question guys…
I found a simple way (not a loop though). Not sure if this is ok but it's working when I added "return".
location.reload();
return;
When adding this command. it simply reloaded once.

location.reload(), Javascript,HTML

I'm having a problem always when I try to use the following code in a button in my HTML file.
onClick=window.location.reload();
mapGenerator();
The page reloads but the javascript (mapGenerator) that make a D3JS view doesn't appear. What am I doing wrong?
location.reload() will immediately reload the page and prevent any following code to execute.
You can, however, create a function that executes your method after the page has (re)loaded:
window.onload = function() {
mapGenerator();
};
This method will run every time the page has fully loaded. To only run the code after you have reloaded the page using location.reload(), you could create a method that handles the click by setting a cookie and then reloading the page.
function handleClick() {
document.cookie="reload=true";
location.reload();
}
This would require you to change your onClick value to onClick="handleClick();". Now, whenever the page loads, you can check whether the cookie has been set. Your window.onload function now changes to this:
window.onload = function() {
if(document.cookie.indexOf("reload") >= 0) {
mapGenerator();
}
}
Checking if a cookie exists - answer by Michael Berkowski
After the reload it's up to you whether you want to unset the cookie — if you don't, the page will run the function mapGenerator on every page load until the cookie expires.
If you need more help with cookies, check out W3Schools' tutorial.
As per your description mentioned above two actions are to be taken on click. As the first action reloads the page the second action is lost. If you want any action to be taken on load of the page, mention the same on onload event of the page.

JS: How to redirect an user to another page when user refresh the page?

The context is a game. When user refreshes his page (F5 or ctrl+R), I want the page to be redirect to gameOver.php page.
Can this be done in pure JS ?
One way to go about is to use a cookie variable as a counter. Every time the user starts the game, you set it to 1 and then increment it on every page load. On page load, you can check the variable's value and redirect using
window.location = 'gameOver.php'
or you can use beforeunload event.
$(window).on("beforeunload", function() {
//your redirect code logic here
})
You can do easily with this code when you want solve with pure javascript:
window.addEventListener("beforeunload", function (e) {
window.location = "gameOver.php";
});
Or you can do with jQuery like below:
$(window).on("beforeunload", function() {
window.location = "gameOver.php";
})
To solve this problem you could use cookies.
As mentioned in this stachoverflow thread, you store a cookie the first time someone visits your page. If you check on every page load if the cookie is set, you can detect if somebody has reloaded the page.
If you plan to create a "Play again" function you can simply destroy the cookie.
To get a look of the code look to the linked stackoverflow question above!
use cookie or localstorage first time someone visits the page. On refresh the check if your cookie or localstorage value is exists and if it does then redirect them to gameOver.php using javascript.
function checkUserVisit() {
if(document.cookie.indexOf('visit')==-1) {
document.cookie = 'visit=true';
}
else {
window.location = "gameOver.php";
}
}
call this function on body load of page.
<body onload="checkUserVisit()">

How to check page is reloading or refreshing using jquery or javascript?

I have to do some kind of operation on the page refresh or reload. that is when I hit next page or Filter or refresh on the grid. I need to show some confirmation box over this Events.
is there any event which can tell you page is doing filer? refresh or paging? using javascript?
Thanks
If it is refreshing (or the user is leaving the website/closing the browser), window.onunload will fire.
// From MDN
window.onunload = unloadPage;
function unloadPage()
{
alert("unload event detected!");
}
https://developer.mozilla.org/en/DOM/window.onunload
If you just want a confirmation box to allow them to stay, use this:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
You can create a hidden field and set its value on first page load. When the page is loaded again, you can check the hidden field. If it's empty then the page is loaded for the first time, else it's refreshed. Some thing like this:
HTML
<body onLoad="CheckPageLoad();">
<input type="hidden" name="visit" id="visit" value="" />
</body>
JS
function CheckPageLoad() {
if (document.getElementById("visit").value == "") {
// This is a fresh page load
document.getElementById("visit").value = "1";
}
else {
// This is a page refresh
}
}​
There are some clarification notes on wrestling with this I think are critical.
First, the refresh/hidden field system works on the beginning of the new page copy and after, not on leaving the first page copy.
From my research of this method and a few others, there is no way, primarily due to privacy standards, to detect a refresh of a page during unload or earlier. only after the load of the new page and later.
I had a similar issue request, but basically it was terminate session on exit of page, and while looking through that, found that a browser treats a reload/refresh as two distinct pieces:
close the current window (fires onbeforeunload and onunload js events).
request the page as if you never had it. Session on server of course has no issue, but no querystring changes/added values to the page's last used url.
These happen in just that order as well. Only a custom or non standard browser will behave differently.
$(function () {
if (performance.navigation.type == 1) {
yourFunction();
}
});
More about PerformanceNavigation object returned by performance.navigation

how to refresh the browser after the page is loaded

I have a scenario to refresh the browser after the page is loaded for first time or one time.
Because the data is not showing properly when the pages is loaded,and when i refresh the browser it is showing.I don't know the reason.
Many Thanks
So you only want the browser to refresh once? Do something like this.
window.onload = function(){
if(!document.location.hash){
window.location = "#loaded";
}
}
or jquery
$(document).ready(function(){
if(document.location.hash){
window.location = "#loaded";
}
});
But in all honesty this is just a temporary solution. As much as you try to cover it up with quick fixes. I guarantee it will come back to haunt you. Well written and structured code will last a lifetime and can always be reused on future projects.
Invariably, you're going to have to use some JavaScript. What you want is for your refresh code to run when the page is completely loaded. You could use the HTML onload event, but there are problems with this (e.g. it will fire before any images are loaded). I would suggest using JQuery's ready() event, if you want to be sure it fires after the entire page is loaded.
Example:
// NOTE: This will only work with JQuery loaded.
$(document).ready(function(){
location.reload(true);
});
Making this only fire on the first page load is a bit more tricky. You could add an anchor suffix to the URL to keep track of whether you've refreshed the page yet or not, and then only refresh if it is not present in the URL:
$(document).ready(function(){
if(location.hash != "#")
{
// Set the URL to whatever it was plus "#".
// (The page will NOT automatically reload.)
location = "#";
// Reload the page.
location.reload(true);
}
});
Alternatively, you could use the query string, since this will automatically refresh the page when changed:
$(document).ready(function(){
var marker = 'r'; // 'r' is for "refreshed"
if(location.search != "?"+marker)
{
// Set the URL to whatever it was plus "?r".
// (This will automatically force a page reload.)
location = "?"+marker;
}
});
Caveat: With either of these samples, if your user bookmarks the page after the "#" or "?r" tag has been added to the URL, the page won't refresh when they revisit the page. If you want it to be bulletproof, you might have to use a cookie instead.

Categories