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");
}
});
Related
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();
}
}
I'm trying to create a session cookie for my media player here in order to track usage and other things the code and the code snippet below isn't creating it at all, (by the way, i'm using one script to create multiple cookies using parameters and want to keep it like that to prevent lengthily scripts)
I've tried a lot of the answers provided in the website already but they don't work, they just result in the same problem
//script to create the 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=/";
}
//for the cookie that makes the name, not part of the question
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 "";
}
// also for the name
function checkCookie() {
var user=getCookie("username");
if (user != "") {
document.getElementById("display").innerHTML = "Welcome back " + user
} else {
document.getElementById("display").innerHTML = "Please enter your name in The prompt at the top of your screen!";
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
window.onload = checkCookie()
//for the session
window.onload = createsession()
function createsession(length){
var sessionnumber = Random rand = new Random();
long drand = (long)(rand.nextDouble()*10000000000L);
setCookie("session", sessionnumber);
};
window.onbeforeunload = function(){
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
};
what I want is for the script to create a cookie that expires at end of the browser session, while being able to keep the other scripts the same to allow me to create multiple cookies without making duplicates of those processing scripts
I created the following fiddle for testing: https://jsfiddle.net/Twisty/toxjLmd8/10/
I added a few things to increase info in console. When I inspect the page and view Storage I can see session cookie and username cookie. If I refresh, I am prompted to enter name again. So it seems to be working as expected.
$(function() {
function setCookie(cname, cvalue, exdays) {
var d = new Date();
if (exdays == undefined) {
exdays = 1;
}
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
console.log("Set Cookie: " + cname + "=" + cvalue, expires);
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 false;
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
$("#display").html("Welcome back " + user);
} else {
$("#display").html("Welcome, please enter your name.");
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
function newSession() {
var sessionnumber = Math.random() * 10000000000.0;
console.log("New Session: " + sessionnumber);
setCookie("session", sessionnumber, 0.0125);
}
function checkSession() {
if (getCookie("session") == false) {
newSession();
}
console.log("Current Session: " + getCookie("session"));
}
window.onbeforeunload = function() {
console.log("Closing - Expire 'username' Cookie");
setCookie("username", "", 0);
};
window.onload = checkCookie();
window.onload = checkSession();
});
Setting a past date or current date and time should have the browser expire the cookie right away and drop it. Setting a cookie with no expiration date can have unexpected results from different browsers. If the date is not set it should expire at the end of the session (the expected behavior) yet the browser may see that it has already expired (still good) or will never expire (really not good). Not all browsers are written the same.
Also if onbeforeunload callback is not triggered, the cookie is not expired but would remain active for 30 days per checkCookie(). You could set the cookie to expire in 20 min (0.0125 days). This is how sessions are handled on the server-side. If the socket closes and the session is idle for 20 min (the default for Session Idle Timeout), the session data is dropped.
Hope this helps.
I am learning about cookies and JavaScript for a student project and have attempted to use them in a school project. However, I have stumbled onto a problem when I try to implement a simple function which bookmarks articles.
This is the code which I place in an article. When I press the bookmark icon, the function below is triggered, creating a cookie that expires after 14 days.
<script>
function showBookmark() {
document.getElementById("bookmark").innerHTML = "bookmark";
var d = new Date();
d.setTime(d.getTime() + (14*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = "cookie1" + "=" + "Article 1 - Title Of Article 1" + ";" + expires + ";path=/";
};
</script>
This is the code which I place in the page where I store and display all the bookmarks the user has made. The code scans through 20 cookies ("cookie1", "cookie2" to "cookie20") and then displays the first 10 cookies where there is a value. The cookies are then displayed in a table using innerHTML().
<script>
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);
} else {
return "false"
}
}
};
var counter=0;
for (var alpha=0; alpha<20; alpha++){
bookmark = getCookie("cookie"+alpha.toString());
if (counter > 10){
break;
}
if (bookmark != "false"){
document.getElementById("bookmark"+counter.toString()).innerHTML = bookmark;
counter++;
}
};
</script>
However, for some reason the code above does not display the intended result (the name of the article does not appear on the page with all the bookmarks even after pressing the icon and triggering the getCookie function). Is there something wrong with my code?
(This is the first question I am asking so any advice would be greatly appreciated)
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;
});
}
});
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>