javascript cookies, create and delete - javascript

I'm working on a page that refreshes itself every 5 minutes
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true" />
On the page is a JS script that should run the first two times the page reloads. When the page reload's for the third time, the script should not execute.
So far, I've created a cookie and given it an initial value of 0, for every refresh I increment it's value (rewrite the cookie) and if the value is smaller than 3 i execute the part of a script. The things is that if I close the tab and reopen the page in another tab, the cookie has the incremented value, and I want it to always start from 0.
Here's what i've done so far:
var value = 0;
$(document).ready(function() {
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 cookieValue = getCookie('siteRefreshCookie');
if (cookieValue !== '') {
var newValue = parseInt(getCookie('siteRefreshCookie')) + 1;
if (newValue < 3) {
//script to be executed
document.cookie = "siteRefreshCookie="+ newValue +";";
}
} else {
document.cookie = "siteRefreshCookie="+ value +";";
}
}
checkCookie();
})

Could I suggest using a query string instead?
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true&count=1" />
Then as an ASP programmer myself I would do something like:
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true&count=<%=CInt(0 & Request.Querystring("count")) + 1%>" />
But you can probably achieve this using PHP, or even JS I imagine if you have no back-end language suitable.
The problem with using cookies is that they are tied to that website, rather than that window. Even if you reset the cookie with an unload function like Pete suggested, you'll then run into problems like if for example you have two tabs open with the same page.

Related

Redirecting post to a different page

I'm writing a simple diary application and I'd like the user to input the entry on one page and have some js script take that entry and collect it into a different page ("diary-posts"). With the code below I can only collect posts within the same page however:
<! DOCTYPE html>
<html lang="en">
<body>
<header class="text-center">
<h2>
Diary Posts
</h2>
</header>
<div class="wrapper text-center">
<textarea id="txt" rows="3" placeholder="How's your day?"></textarea>
<div class="text-l">
<button onclick="getRs()">Create</button>
</div>
<div id="rs" class="wrapper"></div>
<script src="diary-script.js"></script>
</body>
</html>
function _(id){
return document.getElementById(id)
}
function getRs() {
let txt = _('txt').value
const d = new Date()
_('rs').innerHTML += `<div class="card"><p>${txt}</p>
<small>${d.toLocaleTimeString()}, ${d.toLocaleDateString()}</small></div>`
}
How can I modify this in a simple way to achieve what I want?
There is a lot of ways but I recommend you these options. Choose the best one that works for you.
1. Cookie
This option is best if you want it to use in backend too, because you send cookies data to the backend by every requests. so the data must NOT be too large and must be needed in the backend. otherwise you should use the "localStorage".
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 "";
}
setCookie("name", value, 1) //set the cookie for 1 day
getCookie("name") //get the cookie everywhere you want
2. localStorage
If you want to use it only in the user device, this is the option you wanna pick.
note: localStorage stores the data with no expiration date. the data will never ever will be deleted automatically unless you delete it or the user delete it by browser settings.
localStorage.setItem("fieldName", data); //set the item
localStorage.getItem("fieldName"); //get the item
3. sessionStorage (recommended)
sessionStorage is similar to localStorage but the difference is that this will be deleted when user close the browser. so if the data is not so much important and you don't need it next time the user visits the page, this option is made for you.
sessionStorage.setItem("fieldName", data); //set the data
sessionStorage.getItem("fieldName"); // get the data
4. Use backend
you can also store the data in database via backend. you can use an API to send the data to the backend. this option is good for when you need the data in backend and you always need it.

Reading cookie value does only work sometimes

at first i want to make a short description of the process containing the problem:
If someone clicks one of our company's AdWords ads and comes on our website i'm creating a cookie "adwords" with the value "true" via Google Tag Manager (Trigger: URL contains "?gclid="). The cookie is only set with "true", a cookie with "false" is not created at any point.
Then, when someone clicks on our contact form link, i read the value from the "adwords"-cookie and pass it into a blind field in the contact form. When the user clicks the "send" button, i get an email containing his data including the cookie value.
Everytime i try it myself it works perfectly. But when i compare the number of conversions in my AdWords-account with the data i get from my contact form it seems to be working only sometimes for other users.
I'm a beginner in javascript so maybe theres a error in reasoning in my script (its mostly from w3schools):
function getAdwordsCookie(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 "false";
}
function SetAdwordsField() {
proforms.setValue(21,getAdwordsCookie("adwords"));
}
Can someone help please?
use my repository Milk JS in github.
<script src="https://raw.githubusercontent.com/GlowStone07/Milk-JS/main/src/milk.js" type="text/javascript" charset="utf-8"></script>
use the function get then the cookie name, returns cookie value.
FULL EXAMPLE:
//set new cookie
set("name", "John Doe");
//log the cookie's value
console log(get("name'));
//clear all cookies
clear();
//expected output: John Doe
If you want get getCookies function,you can try blow:
function getCookie(c_name) {
if (document.cookie.length > 0) {
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 unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}

Load Magnific Popup once every 15 days for new user

I have a newsletter sign up form that I would like to load (popup) only one time every 15 days, otherwise it might get a bit annoying. I am currently using this jquery code to load the popup form when the page loads.
<div id="test-popup" class="white-popup mfp-hide">
Popup Form
</div>
<script>
jQuery(window).load(function(){
jQuery.magnificPopup.open({
items: {src: '#test-popup'},type: 'inline'}, 0);
});
</script>
This works fine when loading the form every time you access the page but I would like to limit this so new users see it once every 15 days. Not sure if the 15 days is best practice just something I came up with?
You can use localStorage to do this.
$(window).on('load', function() {
var now, lastDatePopupShowed;
now = new Date();
if (localStorage.getItem('lastDatePopupShowed') !== null) {
lastDatePopupShowed = new Date(parseInt(localStorage.getItem('lastDatePopupShowed')));
}
if (((now - lastDatePopupShowed) >= (15 * 86400000)) || !lastDatePopupShowed) {
$.magnificPopup.open({
items: { src: '#test-popup' },
type: 'inline'
}, 0);
localStorage.setItem('lastDatePopupShowed', now);
}
});
<div id="test-popup" class="white-popup mfp-hide">
Popup Form
</div>
You can see a working example here: http://codepen.io/caio/pen/Qwxarw
functions for create and read cookies:
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 = "";
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;
}
create a cookie for 15 days:
createCookie('run_popup',true,15);
check for elapsed 15 days
if(!readCookie('run_popup'))
... code for run popup...
To make your popup open every 15 days for user you probably want to set a cookie that expires every 15 days. On your page, check if cookie has expired, if yes, show your form and reset your cookie.
In this thread you can find material for quick start with cookies.
That will work per browser per computer, ie if user opens your page in other browser, it will load your popup again.

How do I conditionally redirect referrers to different webpages?

I am using a JavaScript "Count down then redirect" script for my website. I want to use something like http referer in the script attached below:
<script>
<!--
/*
Count down then redirect script
By JavaScript Kit (http://javascriptkit.com)
*/
//change below target URL to your own
var targetURL="www.domain.com";
//change the second to start counting down from
var countdownfrom=20;
var currentsecond = document.redirect.redirect2.value =
countdownfrom + 1;
function countredirect() {
if (currentsecond != 1) {
currentsecond -= 1;
document.redirect.redirect2.value = currentsecond
} else {
window.location = targetURL;
return;
}
setTimeout(countredirect, 1000);
}
countredirect();
//-->
</script>
I want the script to work like:
If some one arrive from www.twitter.com, they will be redirected to www.domain.com/twitter.html after the count down.
If some one arrive from www.facebook.com, they will be redirected to www.domain.com/facebook.html after the count down.
If some one arrive from www.youtube.com, they will be redirected to www.domain.com/youtube.html after the count down.
I want to redirect 15-20 URL. Please help !! How can I do it ??
Simple:
var targetURL = /www\.xxx\.com/i.test(document.referrer) ?
"www.domain-for-xxx.com" : "www.domain-for-yyy.com";
Multiple Referrers:
var targetUrl = "http://defaulturl.com/";
if (/www\.xxx\.com/i.test(document.referrer)) {
targetUrl = "http://www.domain-for-xxx.com/";
} else if (/www\.yyy\.com/i.test(document.referrer)) {
targetUrl = "http://www.domain-for-yyy.com/";
}
...

Trouble writing cookie value to form field

Being a Javascript novice I am having some trouble implementing Google's Adwords GCLID tracking on our site. I am following their code examples show here https://support.google.com/adwords/answer/2998031.
You can see the cookie being stored but when trying to retrieve it and populate a hidden form field the result is just blank. I have used other variations but that simply results in "Undefined" as the field value.
Here is the code I'm using
Simplified HTML Form
<form class="signup-form" name="signupform" method="post" action="step2.php">
<input type="hidden" name="gclid" id="gclid" value="" />
</form>
Cookie Write Script
<script type="text/javascript">
function setCookie(a,d,b){var c=new Date;c.setTime(c.getTime()+864E5*b);b=";
expires="+c.toGMTString();document.cookie=a+"="+d+b}function getParam(a) {return(a=RegExp("[?&]"+a+"=([^&]*)").exec(window.location.search))&&decodeURIComponent(a[1].replace(/\+/g," "))}var gclid=getParam("gclid");if(gclid){var gclsrc=getParam("gclsrc");(!gclsrc||-1!==gclsrc.indexOf("aw"))&&setCookie("gclid",gclid,90)};
</script>
Cookie Read Script
<script>
function readCookie(name) {
var n = name + "=";
var cookie = document.cookie.split(';');
for(var i=0;i < cookie.length;i++) {
var c = cookie[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(n) == 0){
return c.substring(n.length,c.length);
}
}
return null;
}
function() {
document.getElementById('gclid').value = readCookie('gclid');
}
</script>
function() {
document.getElementById('gclid').value = readCookie('gclid');
}
this is a function without a name that's never called. try replacing it with only
document.getElementById('gclid').value = readCookie('gclid');
I rewrote your write script, I think your cookie is never set.
function setCookie(a,d,b) {
var c = new Date;
c.setTime(c.getTime()+864E5*b);
b="; expires=" + c.toGMTString();
document.cookie = a + "=" + d + b
}
function getParam(a) {
return(a=RegExp("[?&]"+a+"=([^&]*)").exec(window.location.search))&&decodeURIComponent(a[1].replace(/\+/g," "))
}
var gclid=getParam("gclid");
if(gclid) {
var gclsrc = getParam("gclsrc");
if(!gclsrc||-1 !== gclsrc.indexOf("aw")) {
setCookie("gclid", gclid, 90);
alert("Cookie Set!");
}
}
Working script modified from https://support.google.com/adwords/answer/3285060. I just changed the document.onload to window.onload It seems there was too much going on off screen in the DOM.
<script>
window.onload = function getGclid() {
document.getElementById("gclid").value = (name = new
RegExp('(?:^|;\\s*)gclid=([^;]*)').exec(document.cookie)) ?
name.split(",")[1] : ""; }
</script>

Categories