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>
Related
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
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.
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;
I have tried to create a Javascript cookie in which I am creating and storing the cookie in browser and and checking if cookie is stored on Browser or not. If cookie is stored on browser it will return Welcome user Username otherwise it'll ask user to enter his name.
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;
}
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 "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
<body onload= "checkCookie()">
<input type= "button" onclick= "checkCookie()" value= "val"/>
</body>
This code is prompting again and again to enter the cookie but not storing the cookie in browser
Please have a look at this and find a way to solve this problem?
Thanks
I have to create a JS cookie when a user click a button, this cookie will remember him after 10 minutes with another popup.
Example:
<button>Click me!</button>
and the button will hide when user click, after 10 minutes the button will show again:
<button>Click me!</button>
Script part:
function setCookieMsg(name) {
var d = new Date();
var time = d.setTime(d.getTime() + (600000));
document.cookie = name + "=" + time;
}
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) != -1) return c.substring(name.length, c.length);
}
return "";
}
function checkCookieMsg() {
var cookie = getCookie("name");
var d = new Date() - 600000;
if (cookie == "") {
setCookie("name", cookie);
}else if (d => cookie) {
$().getUnReadMessage();
}
}
What I've wrong?
You didn't mention the expires in cookie. The expires date should be UTC time string.
function setCookieMsg(name) {
var date = new Date();
date.setTime(date.getTime()+(600000));
var expires = "; expires="+date.toUTCString();
document.cookie = name + "=" + expires;
}