I have been working on a script to show an alert box only once (using cookies). Here is what I have so far:
<script type="text/javascript">
function cookie(){
var x = document.cookie;
if (x = "") {
alert("Welcome to Steampunk Inc!");
document.cookie = 'iwashere=iwashere; expires=Fri, 31-Dec-9999 23:59:59 GMT;';
} else if (x = "iwashere=iwashere") {
console.log("You came back!");
}
}
cookie();
</script>
I have this as the first thing in the body of my html file. The code is on the index page on my website here.
The main problem is that you are using = operator with if. = operator assigns value to the variable. Instead you should use == operator to compare.
In addition document.cookie will return all cookies you have stored for your site. You should use some functions to get / set the specific cookies
Here is sample code:
<script type="text/javascript">
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
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 cookie(){
var x = getCookie("iwashere");
if (x == "" || x == null) {
alert("Welcome to Steampunk Inc!");
setCookie("iwashere", "iwashere", 365);
} else if (x == "iwashere") {
console.log("You came back!");
}
}
cookie();
</script>
Related
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.
Is there a way to have my page continuously monitor for a cookie in realtime with Javascript, and if the cookie ever is set then it will send an alert?
The part that I don't understand is how do you check for the cookie in realtime? For example, a user might click a checkbox, a cookie will get set, and then the page to "see" that the cookie is now set and trigger an alert, all in real-time without delay.
Here's an example (not written correctly) that kinda shows what I'm going for.
<div id="click" onclick="setcookie()"></div>
<script>
function checkcookie() {
if (cookie_exists)
alert('cookie exists')
}
</script>
The part that I don't understand is how do I get checkcookie() function to continuously be monitoring for the existence of the cookie I just set with my click?
You have to implement an interval timeout to continuously check for a cookie's value.
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin + prefix.length, end));
return decodeURI(dc.substring(begin + prefix.length, end));
}
// Method used for continuously monitoring a cookie
function monitorCookie(cookieName) {
setInterval(function() {
var cookieValue = getCookie(cookieName);
console.log('Yummy Cookie =' + cookieValue);
}, 500);// monitor cookie every 500 miliseconds.
}
$(document).ready(function() {
monitorCookie("YummyCookie");
});
The only way is to use
window.setInterval("CheckCookie()", 1000);
Which checks for cookie every second
Here are basic functions for writing and reading cookies:
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 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 null;
}
function checkCookie(cname) {
var cookie = getCookie(cname);
if (cookie != null) {
return true;
} else {
return false;
}
}
function remove_cookie(cname) {
document.cookie = cname + '=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;'
}
from w3schools.com/js/js_cookies.asp
My problem seems to be easy but I can't make it work; I want to set a cookie variable called "splash" then display it (later I want use in IF clause)
Here is my code :
<html>
<head>
<script type="text/javascript">
document.cookie = "splash=" + encodeURIComponent("blue theme")
var re = new RegExp(splash + "=([^;]+)");
var value = re.exec(document.cookie);
alert(value);
</script>
</head>
<body>
</body>
</html>
You should change your regex to include splash as part of the quoted string. Even though spash is the variable you're using in the cookie, it does not automatically become a javascript variable.
document.cookie = "splash=" + encodeURIComponent("blue theme")
var re = new RegExp("splash=([^;]+)");
var theme = re.exec(document.cookie)[1];
re.exec returns an array. the first element is the entire matched string (including splash=). The second is your capture group (blue%20theme).
Use Following function to set and get Cookie
function createCookie(name, value, days)
{
if(days)
{
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else
{
var expires = "";
}
var fixedName = '';
name = fixedName + name;
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(name)
{
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
function eraseCookie(name)
{
createCookie(name, "", -1);
}
Using the common code for setting the username and password in cookie via javascript as below -
function submitLogin(){
var uNameInCookie=checkCookie("username");
var passInCookie=checkCookie("password");
if(uNameInCookie!=="" && passInCookie!=""){
document.loginForm.login.value=uNameInCookie;
document.loginForm.passwd.value=passInCookie;
document.loginForm.submit();
}
else{
if(checkInput()){
document.loginForm.submit();
}
}
}
function checkCookie(property){
var x= property;
var prop = getCookie(x);
return prop;
}
function getCookie(cName){
var name = cName + "=";
var cookiez = document.cookie.split(';');
for ( var i=0;i<cookiez.length;i++){
var c= cookiez[i].trim();
if(c.indexOf(name)==0){
return c.substring(name.length,c.length);
}
}
return ""
}
function checkInput()
{
if (document.loginForm.login.value == "")
{
return false;
}
else if (document.loginForm.passwd.value == "")
{
return false;
}
if (document.loginForm.login.value!= "" && document.loginForm.login.value!=null)
{
var usernameValue=document.loginForm.login.value;
setCookie("username",usernameValue,365);
}
if (document.loginForm.passwd.value!= "" && document.loginForm.passwd.value!=null)
{
var passwordValue=document.loginForm.passwd.value;
setCookie("password",passwordValue,365);
}
return true;
}
function setCookie ( cName, cValue, expDays){
var d = new Date();
d.setTime(d.getTime() + (expDays*24*60*60*1000));
var expDate = d.toGMTString();
alert(expDate);
document.cookie = cName + "=" + cValue + ";" + expDate + ";path=/";
}
window.onload=submitLogin();
</script>
the browser is able to auto login the details and submit the form only when I do a logout.
But if I close the browser and hit the url ,the username and password stored in cookie is gone and the form does not auto login.
Is there anything wrong with the code or is it some kind of browser setting. I have added the specific site also to add cookies if needed. Is there anything else that we need to do?
Thanks in advance.
The reason is when you are setting the cookie it's expiration date is not set and it's taking cookie for Session scope. Make correct the following line:
document.cookie = cName + "=" + cValue + "; expires=" + expDate + ";path=/";
I'm having a huge problem with my code, I am trying to check if a cookie exists, and if it does exist, i dont want it to do anything.
Its working fine on page1, but when i navigate to page2 it overrides the cookie, instead of doing nothing (the pages is from the same website)
Heres my script
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g,"");
if (x == c_name) {
return unescape(y);
}
}
}
var omgpost = getCookie("omgpost");
if (omgpost == null || omgpost == "") {
setCookie("omgpost", "1", 1);
} else {
alert('cookie installed already');
}
This is working fine, when I don't have the cookie installed and entering this site, I'm adding the cookie, and I'm getting the confirmation message each time I refresh the page1.
But when navigating to page2 its recreating the cookie??? I don't want that! I want the cookie to be there, and can't be changed, only when it has expired, how can I do that?
Set Cookie Path using path=/
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null)
? "" : "; expires="+exdate.toUTCString())
+ "; path=/";
document.cookie=c_name + "=" + c_value;
}