How can I turn this into a session cookie?
I know I would start by getting rid of the exipredays, but when I set the expiredays to 0 the message cbox displays everytime your refresh the page and I could see that getting annoying..
<p align="center">DISCLAIMER GOES HERE</p>
<script type="text/javascript" language="javascript">
var agreement = GetCookie();
// checks for cookie and displays disclaimer alert if new user
if(agreement=="")
{
var decision = confirm("DISCLAIMER: GOES HERE \n\nClick Ok if you agree to the disclaimer or click Cancel to close this window. \n");
if(decision == true)
{
// writes a cookie
var expiredays = 7;
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie="PartnerAgreement"+ "=" +escape("Agree To Disclaimer")+
((expiredays==null) ? "" : "; expires="+exdate.toGMTString())
}
else
{
// redirect
window.location = "/_layouts/signout.aspx";
// or close the browser window
//window.opener='x';
//window.close();
}
}
// gets the Cookie if it exists
function GetCookie()
{
if (document.cookie.length>0)
{
c_name = "PartnerAgreement";
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return agreement = unescape(document.cookie.substring(c_start,c_end))
}
}
return "";
}
Your code says:
((expiredays==null) ? "" : "; expires="+exdate.toGMTString())
0 is not null (0 is "immediately"). Set expiredays to null.
Related
I'm attempting to create a redirect based on a cookie existence. So when a user connects to my website jonathanstevens.org for the first time, they are redirected to jonathanstevens.org/landing
Code parts:
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
Global.js
function create_cookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime( date.getTime() + (days*24*60*60*1000) );
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function get_cookie(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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Index.html
<!-- redirect to landing page -->
<script>
// Redirect to landing page if 'form_submitted' cookie does not exist
if (get_cookie('secondvisit') === 'undefined') {
window.location.href = "landing.html";
}
</script>
landing.html
<!-- Adds second Visit cookie -->
<script>
jQuery(document).ready(function($) {
// Create cookie so that the user is no longer redirected
create_cookie('secondvisit', 'true', 30);
});
</script>
The expected result was it to check for a cookie, then forward me to my landing page if it wasn't defined. Any ideas on what I've done wrong?
You should compare with null instead of undefined as you are returning null from the function get_cookie
Index.html
<!-- redirect to landing page -->
<script>
// Redirect to landing page if 'form_submitted' cookie does not exist
if (get_cookie('secondvisit') === null) {
window.location.href = "landing.html";
}
</script>
Apart from this you should use this library really good one an easy to work with see below
Create a cookie, valid across the entire site:
Cookies.set('name', 'value');
Create a cookie that expires 7 days from now, valid across the entire site:
Cookies.set('name', 'value', { expires: 7 });
Create an expiring cookie, valid to the path of the current page:
Cookies.set('name', 'value', { expires: 7, path: '' });
Read cookie:
Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined
Read all visible cookies:
Cookies.get(); // => { name: 'value' }
Delete cookie:
Cookies.remove('name');
Delete a cookie valid to the path of the current page:
Cookies.set('name', 'value', { path: '' });
Cookies.remove('name'); // fail!
Cookies.remove('name', { path: '' }); // removed!
EDIT
A converted version of your code using js.cookie library will look like following.
(Note: i have tested this code and it works correctly, make sure you are including the library correctly and there are no errors on the console.)
Index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>
<!-- redirect to landing page -->
<script>
$(document).ready(function () {
if (typeof Cookies.get('secondvisit') === 'undefined') {
window.location.href = "landing.html";
}
})
// Redirect to landing page if 'form_submitted' cookie does not exist
</script>
landing.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>
<!-- Adds second Visit cookie -->
<script>
jQuery(document).ready(function () {
// Create cookie so that the user is no longer redirected
var a = Cookies.set('secondvisit', 'true', {
expires: 7
});
});
</script>
I have an application that needs to pop a URL based on a Query String sent to it. Unfortunately, we can't insert any javascript into the application itself, but we can insert an iFrame that loads a page running javascript. There is a bug in the application where it loads the content in the iFrame twice within a couple seconds, which results in the URL popping twice.
To resolve this, I decided to set a cookie with an expiration. Before popping, I would check to see if the cookie exists, and if it does, prevent the pop from happening.
Unfortunately, my cookie is not being set. I've read a few threads about Javascript cookies trying to figure this out. The first thing I found is Chrome does not accept cookies from local files, so I set up an IIS server to host the page.
However, the cookie still is not being set. I read this page to make sure my code was correct, and as far as I can tell, it should be correct.
The code for my page is below. Any help would be greatly appreciated.
<html>
<head>
<script type="text/javascript">
var isPopped;
function myFunction() {
alert("Hello! I am an alert box!");
}
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, 30);
}
}
}
function pop() {
var queryString = location.search.substring(1); //Get Query String from URL of iFrame source. The substring(1) strips off the ? and only takes the first substring. This can be modified to take more and the resulting string can be edited with Regular Expressions if more flexibility is required.
var urlToPop = "https://www.google.com/#" + queryString //Set URL to pop.
var recentVisitTrue=getCookie("visitRecent");
if (recentVisitTrue != "") {
isPopped = 1;
} else {
window.open(urlToPop,"_blank");
setCookie("visitRecent", "true");
}
}
function setCookie(cName,cValue) {
var date = new Date();
date.setTime(d.getTime() + 8000000);
var expires = "; expires=" + date.toGMTString();
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 "";
}
</script>
</head>
<body onload="pop();">
v0.32
</body>
</html>
Thanks!
Hi everyone i want to redirect a user to another page if the cookie is set by clicking the button.
<a href="" onClick="SetCookie('pecCookie','dit is een cookie','-1')"><button type="button" name="accept" class="btn btn-success">Button Text</button>
<script>
function SetCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+365)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) +
("; path=/")
location.reload()
}
if
</script>
Works and i also got the if statement in php but i want it in javascript because of wordpress issues. In php it would look like this.
<?php
$cookie_name = "anyname";
$cookie_value = "anycontent";
If (isset($_COOKIE[$cookie_name])) {
// action if cookie is set
}
?>
i can't seem to figure it out in javascript, and i also looked around on the web
After doing this:
<a href="" onClick="SetCookie('pecCookie','dit is een cookie','-1')"><button type="button" name="accept" class="btn btn-success">Button Text</button>
<script>
function SetCookie(c_name,value,expiredays) {
var exdate=new Date()
exdate.setDate(exdate.getDate()+365)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) +
("; path=/")
location.reload()
}
mycookieValue = getCookie("pecCookie")
if(mycookieValue) {
window.location = "193.91.113.21/downloads/";
}
function getCookie(c_name) {
var re = new RegExp(c_name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
</script>
it keeps going to the redirect even without the cookie
Here is a function for get the cookie value in javascript.
mycookieValue = getCookie("mycookieName")
if(mycookieValue)
{
//Your code here
}
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
I will suggest you use jQuery cookie.js library. You can download it from here.. https://github.com/carhartl/jquery-cookie
Example:
//Set Cookie
$.cookie('userName', 'John');
//Read Cookie Value
var username= $.cookie('userName');
console.log(username);
//Remove a cookie
$.removeCookie('username');
//Cookie is removed then above line will return true
//Check cookie in if else
if(username){
console.log(username);
}
// or you can do this also
if(username=='John'){
console.log('User Name is '+username);
}
Hope this will help you.
I'm trying to do a demo test on javascript cookie. Please find the code below which I wrote for testing.
<html>
<head>
<script type='text/javascript' >
function setcookie()
{
alert("check if cookie avail:" +document.cookie.split(';'));
var dt=new Date();
document.cookie='name=test';
document.cookie='expires='+dt.toUTCString()+';'
alert("now cookie val:" +document.cookie.split(';'));
dt.setDate(dt.getDate()-1);
document.cookie = "expires=" + dt.toUTCString() + ";"
alert("after deletion cookie val:" + document.cookie.split(';'));
}
</script>
</head>
<body>
<input id='txt' onchange='setcookie()' />
</body>
</html>
The code will work as,
Initally, this will display the cookie which is present already in that browser, then I try to set a cookie as 'name=test' with 1day expire time. Using alert I can see the value set in that cookie. In the next line, I try to delete cookie by setting expire date to current date-1. If I use alert to print the cookie value, cookie is displayed with expire date as currentdate-1.
My questions is,
In Mozilla, If I refresh the browser and try to do the same step then the first alert displays the cookie value with expire time as currentdate-1. Why Im getting cookie value even if i delete at the last line of my script. However, once I close the browser the cookie value is empty. Why it is so?
In chrome, If I run the same piece of code, neither of the cookie is set. Why Im not able to set cookie in chrome browsers.
Please tel me why such difference occuring across browsers.
This is not setting the expiry
document.cookie='name=test';
document.cookie='expires='+dt.toUTCString()+';'
this is
document.cookie='name=test; expires='+dt.toUTCString()+';'
The best is to take well tested cookie code and use that
Try this one or use a jQuery plugin if you use jQuery
// cookie.js file
var daysToKeep = 14; // default cookie life...
var today = new Date();
var expiryDate = new Date(today.getTime() + (daysToKeep * 86400000));
/* Cookie functions originally by Bill Dortsch */
function setCookie (name,value,expires,path,theDomain,secure) {
value = escape(value);
var theCookie = name + "=" + value +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((theDomain) ? "; domain=" + theDomain : "") +
((secure) ? "; secure" : "");
document.cookie = theCookie;
}
function getCookie(Name) {
var search = Name + "="
if (document.cookie.length > 0) { // if there are any cookies
var offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
var end = document.cookie.indexOf(";", offset)
// set index of end of cookie value
if (end == -1) end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
function delCookie(name,path,domain) {
if (getCookie(name)) document.cookie = name + "=" +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
";expires=Thu, 01-Jan-70 00:00:01 GMT";
}
I want to establish if a determinated page of my web site is currently opened, from others web page. All on client's side (thus all by Js Code).
I tried to write the following code, but it doesn't behave as expected.
function setCookie (name, value, seconds)
{
if (typeof(seconds) != 'undefined') {
var date = new Date();
date.setTime(date.getTime() + (seconds*1000));
var expires = "; expires=" + date.toGMTString();
}
else {
var expires = "";
}
document.cookie = name+"="+value+expires;
}
function web_page_alive()
{
setCookie("page_alive","true", 3);
}
page_alive_schedule=self.setInterval("web_page_alive()",1000);
So, every second, the "page_alive" cookie is set to true with an expires time of 3 seconds.
Thus, as long as the web page will remain opened, the cookie will be set to true.
When the user closes the web page, in 3 seconds the cookie should be destroyed by the browser. Strangely the cookie remains set ( with a "back" expires time ) also when i close the page. I'm using FF 11. Does anyone know how is this possibile? Thank you all.
This is working correctly for me.
Open both setter.html and checker.html (below) in your browser.
Every fifteen seconds checker.html will check the value of the cookie and alert it.
As long as setter.html is open and setting its cookie, checker.html will display true.
But once you close setter.html, then checker.html will display undefined.
Here is setter.html:
<html>
<head>
<script type="text/javascript">
function setCookie (name, value, seconds)
{
if (typeof(seconds) != 'undefined') {
var date = new Date();
date.setTime(date.getTime() + (seconds*1000));
var expires = "; expires=" + date.toGMTString();
}
else {
var expires = "";
}
document.cookie = name+"="+value+expires;
}
function web_page_alive()
{
setCookie("page_alive","true", 3);
}
page_alive_schedule=self.setInterval("web_page_alive()",1000);
</script>
</head>
<body>
<p>This is the setter.</p>
</body>
</html>
And here is checker.html
<html>
<head>
<script type="text/javascript">
// from http://www.w3schools.com/js/js_cookies.asp
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);
}
}
}
function web_page_alive()
{
var value = getCookie("page_alive");
alert(value);
}
page_alive_schedule=self.setInterval("web_page_alive()",15000);
</script>
</head>
<body>
<p>This is the checker.</p>
</body>
</html>
Note, using getCookie from w3schools.com