Refresh page ONCE - javascript

I would like to implement a JavaScript code which states this: if the page is loaded completely, refresh the page immediately, but only once. This one works fine:
window.onload = function() {
if(!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
}
but I don't want hash at the end. Any solution?

use cookies or localStorage
window.onload = function() {
if(!localStorage.loaded) {
localStorage.setItem('loaded', 'yes')
window.location.reload();
}
}

If first time will loaded then you have to set the hash ('loaded'). The automatically will reload the page. Second time he will found the hash #loaded in the url and dont reload the page again.
To avoid hash in the url you can use cookie or localStorage.
LocalStorage: In this case take a look to the answer from #uingtea: https://stackoverflow.com/a/71373469/14807111.
window.onload = function() {
if(window.location.hash !== '#loaded') {
window.location.hash = '#loaded';
window.location.reload();
}
}
With cookie
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
let expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
window.onload = function() {
if(getCookie('loaded')) {
setCookie('loaded','true',180);
window.location.reload();
}
}

Related

Set cookie with array() in jquery

I would like to be able to check if a cookie (id) is set or not: if not set, then create it. If set, retrieve the value (= an array). How can I retrieve the array from the cookie?
I hear that I would have to use JSON, but I'm not sure how that would work with the following code?
function start(id){
if (document.cookie.indexOf('id') === -1 ) {
setCookie('id', id, 7);
}
else {
var playedID = [GET COOKIE ARRAY]
playedID.push(id);
setCookie('id',playedID);
}
}
Here's a way to do it based on some helper functions to make sure you are parsing and stringifying the cookie correctly.
getCookie and setCookie are from https://www.w3schools.com/js/js_cookies.asp
// This won't run due to security policies on this site, but you can run it in the dev tools and see.
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookieArray(cname) {
var cookie = getCookie(cname);
return cookie ? JSON.parse(cookie) : [];
}
function pushToCookieArray(cname, cvalue, exdays) {
var cookieArray = getCookieArray(cname);
cookieArray.push(cvalue);
setCookie(cname, JSON.stringify(cookieArray), exdays);
}
function start(id) {
pushToCookieArray('id', id, 7);
console.log(getCookieArray('id'));
}
start(5);
start(6);
start(8);
First a cookie is not stored as an array but a string : if you type document.cookie in you console, you will get all the cookies from the website you are visiting, separated with a coma.
So as explained here : https://www.w3schools.com/js/js_cookies.asp,
you will have to create a custom function to access the cookie you need.
Then the value of you cookie is still a string, so as explained here if you want to save an array of ids, you have to use JSON.stringify to encode you array as a string : I want to store Javascript array as a Cookie
You can then create it or update its value :
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function setCookie(cname, cvalue) {
document.cookie = cname + "=" + cvalue + ";";
}
function start(id){
if (getCookie('id') === '' ) {
setCookie('id', JSON.stringify([+id]));
}
else {
let ids = JSON.parse(getCookie('id'))
console.log(ids)
ids.push(+id);
setCookie('id', JSON.stringify(ids));
}
}
function sendID(id) {
console.log(document.getElementById("user-id").value)
start(id);
alert(getCookie("id"))
}
Here is a working example : https://codepen.io/adrientiburce/pen/ExVbYWy?editors=1010

How do i show output from cookies?

Hi i have one problem:
I have fully functioning cookies on my site, but I do not know how to display their content that the user wrote to them
My code is as follows:
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
} else {
user = prompt("BlaBlaBla","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
And i need to display it into <h1> tag there:
<h1 class="heading white"><br>Hi
**THERE**
</h1>
<br>
The cookie name that i want to show is "username" or "user"
I will be happy for any suggestions for putting cookies in place because I search the internet all day and I do not know the advice
Get the cookie and then just inject it into the html... I would add an ID to the html h1 tag.
var user = getCookie("username");
//This won't really work because the id isn't called that
var h1 = document.getElementById("heading white");
h1.innerHTML = user;

cookies aren't being stored after page change

I am storing cookies from form values using the below code. I can see that the cookies have been stored when I look under Application > Cookies in developer tools. When you press submit on this form, it takes you to the start of a survey. The pages of the survey are within the same file path of the form page. After the first page of the survey loads, I check in developer tools and the cookies aren't there. This only happens randomly, but I've found that it happens much more often on Macbooks using Chrome. I am on a pc using chrome and it's never happened to me.
// Script to set cookies
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// Script to get cookies
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
//Check for enabled cookies
function areCookiesEnabled() {
document.cookie = "__verify=1";
var supportsCookies = document.cookie.length >= 1 &&
document.cookie.indexOf("__verify=1") !== -1;
var thePast = new Date(1976, 8, 16);
document.cookie = "__verify=1;expires=" + thePast.toUTCString();
return supportsCookies;
}
//Set cookies on form submission
$(document).ready(function() {
$( "#fn-2" ).change(function() {
setCookie("firstName", this.value, 30; path=appfire.com/club);
});
$( "#ln-2" ).change(function() {
setCookie("lastName", this.value, 30);
});
$( "#eml-2" ).change(function() {
setCookie("email", this.value, 30);
});
});
$("#wf-form-club_profile_creator").submit(function(e){
e.preventDefault();
if (areCookiesEnabled() ) {
console.log('Cookies are enabled.');
window.location.replace("http://www.appfire.com/club/quiz/q1");
} else {
console.log('Cookies are disabled');
alert('Cookies appear to be disabled in your browser. To create your A List club profile, please enable cookies and try again. Thanks!');
window.location.replace("http://www.appfire.com/club");
}
});

Only show jQuery once per session

So I use the following code to show and fade an element. I have set the div on visible on the homepage and hidden on all other pages so the div only shows up on the homepage. My problem is, everytime I visit the homepage, the div will show up. Instead I would like to show the div only once per session. I've tried to fix it with cookies but it didn't work.
$(window).load(function(){
$("#testlay").fadeIn('slow').delay(1000).fadeOut(1600);
});
You can use coockie for this take a look at below example hope it helps
Please find this fiddle for the same
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = "; expires=" + date.toUTCString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
//your window load function replace with below
$(function(){
if(readCookie('CodefireOnce') == null)
{
createCookie('CodefireOnce','true',7);
$("#testlay").fadeIn('slow').delay(1000).fadeOut(1600);
}
});
You can use localStorage which would be more right in this case IMO.
$(window).load(function(){
if(typeof localStorage.testlayHidden != 'undefined') {
$("#testlay").fadeIn('slow').delay(1000).fadeOut(1600, function() {
localStorage.testlayHidden = 1;
});
}
});

how to know if a user has a certain cookie using javascript

I have been stuck on this problem for a couple hours now, and cant seem to get off of it. I have a html website where i'm giving a user a cookie called "schoolid" and it has the school's ID in it. If a user has a certain school ID, in this case "gms08",they will be redirected to another website. This is what i have so far in the cookie area.
I have a check cookie function checking to make sure the user has it, but i cant seem to get it to pick up on the fact that the user has the cookie and it is gms08.
i.stack.imgur.com/wQjnx.png
Pastebin: http://pastebin.com/Gfjc7iTG
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
</script>
<script>
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
</script>
<script>
function checkCookie() {
var id = getCookie("schoolid");
if (id != "") {
alert("Welcome again ");
} else {
alert("user");
}
}
</script>

Categories