Run script with timeout once per session (but you could reload page and go to another page) - javascript

I've got a simple script, that I need to run only once per session of user. But in this session he could refresh page, or go to another page on one site.
My code now looks like this, but if user refresh page (in less then 10 seconds) or go to another page - script will never run :(
var visited = sessionStorage.getItem('visit');
if (visited == null || document.location.href == sessionStorage.getItem('lastPage')) {
setTimeout(function() {
alert('Hello World')
}, 10000
)
sessionStorage.setItem('visit', 1);
};
Working example: https://codepen.io/zavtraleto/pen/GdRpRZ
I think it's something with cookies, maybe

I made it using cookie, so if everyone interested:
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);
}
}
}
getCookie('user_first_visited') || setCookie('user_first_visited', Date.now());
if (!getCookie('user_popup_triggerred')) {
var loopDetect = setInterval(function(){
var TimePast = (Date.now() - getCookie('user_first_visited')) / 1000;
if( TimePast > 5){
if (localStorage.getItem('surveyOnce') !== 'true') {
(function() {
alert('Hello World!')
}
)();
localStorage.setItem('surveyOnce','true');
};
}
}, 1000);
}

Related

javascript counter with cookies doesn't work

I just tried to make a timer with cookies that makes a button only 3 times clickable (I had to do it with cookies cause it refreshes the page in its process), I made this timer but it doesn't work. Nothing on my page changed at all.
The code I have by //something else happens gets executed by the program.
Timer - (or at least what I thought that would work as a timer) :
mailagain.onclick = function () {
if (typeof getCookie("countIt") !== 'undefined') {
if (checkCookie("countIt") > 3) {
// something happens
} else {
//something else happens
var counter = checkCookie("countIt") + 1;
setCookie("countIt", counter, 1)
}
} else {
setCookie("countIt", 1, 1)
}
};
Coockie functions :
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 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(name) {
var value = getCookie("name");
if (value != "") {
return value;
}
}
Some issues:
When reading the value from the cookie, be aware that it has the string data type. You need to convert it to number before comparing it with another number or adding 1 to it.
The function checkCookie is using the wrong (hard-coded) cookie name, but is even not necessary as a function. You can do all that with getCookie.
Here is a working version:
mailagain.onclick = function () {
// make sure to convert to number (unitary plus), or use 0 when it is not a number:
var counter = (+getCookie("countIt") || 0) + 1;
setCookie("countIt", counter, 1)
if (counter > 3) {
console.log('clicked too many times! (', counter, ')');
} else {
console.log('clicked ' + counter + ' number of times.');
}
};
var value = getCookie("name");
getCookie always return "undefined" because of wrong cookie name. Remove brakets.
function checkCookie(name) {
var value = getCookie(name); //here you go
if (value != "") {
return value;
}
}

Detect if cookies are enabled in the browser

The code below works in all current browser except for IE. In IE the message doesn't display.
if (navigator.cookieEnabled == 0) {
document.write("Cookies are not enabled.");
}
Can someone tell me what I can do to make the above code work in IE 10 & 11?
I've tried code that works in IE but then it works in most browser except for Safari. Here's the code.
<script type="text/javascript">
if(/MSIE \d|Trident.*rv:/.test(navigator.userAgent))
var cookies = ("cookie" in document && (document.cookie.length > 0 ||
(document.cookie = "test").indexOf.call(document.cookie, "test") > -1));
document.write(cookies ? "" : "Cookies are not enabled.");
</script>
But this still displays for FF, Safari, and Chrome. So then I have two messages displaying....
This will do it:
$(document).ready(function () {
var event = window.attachEvent || window.addEventListener;
if (!trySetCookie()) {
// cookies are disabled
}
else{
// cookies are enabled
}
}
function trySetCookie() {
setCookie("testCookie", "testValue", 1);
var cookieValue = getCookie("testCookie");
if (cookieValue == "" || cookieValue == null)
return false;
return true;
}
// set a test cookie in the user's browser
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=/";
}
// read the test cookie
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 "";
}
"$(document).ready()" in JavaScript

How do I get a cookie from user input, and display it on an html element

I'm making a website that uses a cookie to get the user's name. When I try to get it to be shown with inner.html, it won't even prompt the user. Here is my code. The area is specific is the function checkCookie()
<!DOCTYPE html>
<html>
<head>
<script>
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;
}
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 != null) {
document.getElementById("person").innerHTML =
"Hello " + user + "!";
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
<p id="person">anonymous user</p>
</body>
</html>
Change
return "";
to:
return null;
checkCookie expects getCookie to return null when the cookie isn't found. An empty string is not the same as null.
DEMO

Teamspeak connect button and choose nickname

So I want to have a connect button that let's you join the server from a Web browser and when you click it, there is a popup that lets you choose your nickname. Also I want there to be a cookie that saves the username so you don't have to enter it every time.
Can this be done with only javascript in HTML?
Thanks
Here is a terrible bit of code I copied & pasted and modified for you. It is not exactly what you want but it should still work. You could make a button that opens a page in a new url with this code:
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*10000000));
var expires = "expires=" + d.toGMTString();
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 + ". You will now be redirected to our teamspeak server.");
window.location.assign("ts3server://ts.specternetworks.com?port=9987&nickname=" +user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
window.location.assign("ts3server://ts.specternetworks.com?port=9987&nickname=" +user);
}
}
</script>
<body onload="checkCookie()">
</body>

Redirect if cookie is null

So I'm now learning about cookies and and got my cookie code form this page on w3schools.com.
Here on StackOverflow I looked up about redirecting and I've attempted to redirect to here is the cookie has not been set. This will redirect to a page on my server to accept cookie policy and customize the admin panel theme.
<!-- Javascript BEFORE page loads Starts -->
<script type="text/javascript">
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("Cookie Set: " + user);
} else {
//user = prompt("Please enter your name:","");
if (user != "" && user != null) {
window.location.replace("http://stackoverflow.com");
}
}
}
</script>
<!-- Javascript BEFORE page loads Starts -->
</head>
<!-- Header Ends -->
<!-- Body Starts -->
<body onload="checkCookie()">
Why are you checking for user!="" && user!= null in the else block? the user variable is guaranteed to be empty when code enters in this block. This is why window.location.replace isn't executing and the reason why its not redirecting.
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 checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Cookie Set: " + user);
} else {
//user = prompt("Please enter your name:","");
setCookie("username", "value", 1);
window.location.replace("http://stackoverflow.com");
}
}

Categories

Resources