JavaScript login with cookies - javascript

I've been trying to figure out how to do one of the tasks that im given for the past 3 hours and I just can't seem to do it.
This is the task:
Add a login page (login.html) with a login form to the system. When logging in, it creates
a cookie in which the username, password and duration of the login cookie are saved. While there is a login cookie, other sites can be visited. If the cookie doesn't exist it switches to login.html from either page. Clicking on logout deletes the login cookie (moves us back to the login.html) .
this is my HTML code for the login form:
<form action="index.html" id="loginForm" method="post">
<div>
Username: <input type="text" name="uname" id="uname">
</div>
<div>
Password:<input type="text" name="pwd" id="pwd">
</div>
<div>
<button type="submit" id="myBtn"> Sign in </button>
</div>
</form>
Hope someone could help me, I've got little time left. Thank you in advance! :,)

document.querySelector('#loginForm').addEventListener('submit', () => {
setCookie('user', document.querySelector('#uname').value, '/')
setCookie('pass', document.querySelector('#pwd').value, '/')
})
if(!getCookie('user')||!getCookie('pass')) if(location.href != 'https://somelocation.example/index.html/') location.replace('https://somelocation.example/index.html/')
// Cookies setting and getting functions
function setCookie(name, value, path, options = {}) {
options = {
path: path,
...options
}; if (options.expires instanceof Date) {
options.expires = options.expires.toUTCString();
} let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value)
for (let optionKey in options) {
updatedCookie += "; " + optionKey
let optionValue = options[optionKey]
if (optionValue !== true) {
updatedCookie += "=" + optionValue
}
}
document.cookie = updatedCookie;
}
function getCookie(name) {
let matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : undefined
}
Explaining:
1.0 Event:
There is event to set values in cookie when using submitting form (functions explaining at 1.2)
1.1 Checking cookies:
Then there is checking if cookie "user" and "pass" do not exist, then you are being redirected
1.2 Functions:
1.2.0 setCookie:
First we are getting path and options that user set, then checking if expires function is in Date format (e.g. 1653420565221), and if it's true then converting to UTC string. (Skipped part with for...in loop because not in use) After all, cookies setting to new one.
1.2.1 getCookie:
Just getting and encoding cookie property using match(), and if it's not exist, returning undefined.

In my experience, you need to use PHP and a database because if you just use javascript, the users won't be able to access their accounts if they simply clear their cookies.
Sorry for not being very insightful on how to answer your question, but PHP would be the first step, someone else can elaborate on how to get the PHP set up, because it is not my specialty.
Edit:
<!DOCTYPE html>
<html>
<head>
<script>
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 "";
}
function checkCookie() {
let user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()"></body>
</html>
source of code: w3schools

Related

cookie possibly blocking clipboard API

I have this bit of code below that essentially on click of an a tag copies the text of an input field to the clipboard and then opens a new tab where the user pastes the text.
This all works completely fine UNTIL the cookie is set. I have tried it with testing 10 of the different a tags before the cookie is set.
Once the cookie is set, the new tab will still open, the input field I am copying the text from still updates, but if I paste into notepad or the window that opens, it will be whatever was copied last and not the most up to date. If I remove the cookie and reload everything goes back to how it should function.
So I am not sure why the cookie being set would stop the clipboard from updating.
//Set Cookie Function
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=/";
}
//Get Cookie Function
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));
}
$(document).on('click', '.pop-top ul li a', function() {
var copiedRole = $(this);
$('#copyText').val(copiedRole.text());
navigator.clipboard.writeText($('#copyText').val());
var acknowledgeExists = getCookie("acknowledge");
if(acknowledgeExists == null) {
$('#copyMessage, .frosted').addClass('show');
} else {
window.open('[redacted]', '_blank');
}
});
//Create Cookies
$("#acknowledge").on('click', function() {
$('#copyMessage, .frosted').removeClass('show');
window.open('[redacted]', '_blank');
if($('#never').is(':checked')) {
setCookie("acknowledge", "yes", 1);
}
});
So it turns out that it was not the cookie, but the window.open firing immediately. MDN docs for the clipboard API note that the tab must be active. So even though my code has the write to clipboard function before the cookie check, it still would fire quick enough to prevent it.
While not an ideal solution wrapping the window.open in the cookie if/else in a setTimeout for 1 second works fine.

Set a cookie for an iframe popup to keep it closed

I'm using TypeForm to handle my lead generation forms. The form I'm using has been embedded on the home page of my site. This embedding creates an iframe showing the popup every time the home page is loaded, even if the 'X' is clicked.
Having contacted TypeForm, I have been told that I would need to set a cookie to prevent the popup loading each time. In fact their reply was "To ensure the Typeform only appears once you will have to add cookies to your site in order to ensure a user only sees it one time. This isn't a feature we currently have but hopefully with more requests it's something we could add!"
Embed Code:
<a class="typeform-share button" href="https://example.typeform.com/to/fbPnzs" data-mode="drawer_left" data-auto-open=true target="_blank" style="display:none;"></a>
<script>
(function() {
var qs, js, q, s, d = document,
gi = d.getElementById,
ce = d.createElement,
gt = d.getElementsByTagName,
id = "typef_orm_share",
b = "https://embed.typeform.com/";
if (!gi.call(d, id)) {
js = ce.call(d, "script");
js.id = id;
js.src = b + "embed.js";
q = gt.call(d, "script")[0];
q.parentNode.insertBefore(js, q)
}
})()
</script>
The embed URL is example.typeform.com whereas the website where the form is to be embedded is not the same. Does consideration need to be made about same-origin?
What do I need to implement in terms of code to the functions.php file of my WordPress site to add a cookie that allows the popup to show only once and/or never show again if the 'X' is clicked?
Thank to Nicolas for his answer!
Having checked over the SDK, I've adapted Nicolas' snippet to cater to the left draw popup. This checks if a cookie exists, if it does not, it should set it and display the left draw TypeForm popup; if the cookie does exist, it won't show.
var url = "https://demo.typeform.com/to/njdbt5" // Update with your TypeForm URL
let params = new URLSearchParams( location.search );
url += "?utm_source=" + params.get( 'utm_source' ); // Replace with the hidden values you want to pass
var displayed = getCookie( "typeform_displayed" ); // Check for the cookie typeform_displayed
if ( displayed ) {
null
} else if ( !displayed && displayed === "" ) {
setCookie( "typeform_displayed", true, 365 ); // Set typeform_displayed cookie with a value of true and an expiry of 365 days
showEmbed();
}
//
function showEmbed() {
window.typeformEmbed.makePopup( url, {
mode: 'drawer_left',
autoOpen: true,
hideHeaders: true,
hideFooters: true,
} )
}
// Cookie Manipulation
// Source: https://www.w3schools.com/js/js_cookies.asp
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 "";
}
I think this is totally doable using Typeform Embed SDK.
You will need to check if the cookie is already set. And depending on the value display or not the embed typeform.
I made a working example on Glitch, you can look at it here.
In code the logic would look like this:
var displayed = getCookie("displayed_typeform");
if (displayed){
embedElement.innerHTML="<h2>Typeform already displayed once.</h2>"
} else if (!displayed && displayed === "") {
setCookie("displayed_typeform", true, 365);
showEmbed();
}
Hope it helps :)

I am trying to create popup div for one time load on whole website

This is popup-up div and it's working good. But it's load every time after I refresh the browser and what I want? I need this only one time when user open my website.
Any idea how to control this. FYI this is magento-2 popup.
require(
[
'jquery',
'Magento_Ui/js/modal/modal'
],
function(
$,
modal
) {
var options = {
type: 'popup',
responsive: true,
innerScroll: true,
//title: 'popup modal title',
buttons: [{
text: $.mage.__('Continue'),
class: '',
click: function() {
this.closeModal();
}
}]
};
var popup = modal(options, $('#popup-modal'));
$('#popup-modal').modal('openModal');
}
);
$(document).ready(function() {
$(".actions").click(function() {
alert("The paragraph was clicked.");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup-modal">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<h1>Subscribe for Our <span>exclusive offer</span></h1>
<p>Be the first to know about new arrivals exclusive offers and promotions</p>
<?php echo $block->getLayout()->createBlock('Magento\Newsletter\Block\Subscribe')->setTemplate('subscribe.phtml')->toHtml();?>
</div>
Since normal JavaScript (actually NodeJS works server side) only handles client side operations (i.e. your browser), it cannot "remember" that a pop-up was shown once after a page reload. JavaScript need some kind of help for it. The point is that you do not need to care about the JavaScript part that much, but more about PHP in this case.
1.: You could save this information in a cookie, which could save the information if a pop-up was shown once. Only downside is that when you clear your browser cookies, the pop-up would come up again.
2.: You could you the MySQL Database to store this information permanently. Therefore you would need your own custom module though. Good examples can be found in the search.
My recommendation is to create your own module if you haven't already and extend the database table for customers with your information.
Hope this helps you to get in the right direction.
Add cookie there are some functions related to CREATE ,READ and REMOVE cookie please find this fiddle or below snippet for more information.
I hope it'll help you
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = "; expires=" + date.toUTCString();
}
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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
$(function(){
if(readCookie('OnlyONCE') == null)
{
$('#popup-modal').modal('openModal');
createCookie('OnlyONCE','true',7);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cookie" style="display:none;">POP UP
<a href="#" class="cookie-close">
<span class="icon" onclick='onClose()'>X</span>
</a>
</div>

Countdown clock not reset on refresh

I have a countdown clock here that resets when the page is refreshed. I would appreciate it if someone could help me?
I have included the script below.
<script type="text/javascript">
var ticker = function() {
$("#ticker").css({
left: "120%"
}).animate({
left: "-420px"
}, 6000, 'linear', ticker);
}
ticker();
</script>
Considering you need it to be "running" while user is not in the page, I will point out that Javascript is a client side scripting language Javascript code is run in local side i.e its interpereted by the browser. This makes hard to "keep" track of things if the user refreshes the page until unless you have have stored them somewhere. There can be different approaches for your solution such as:-
LocalStorage
Cookies
Server Side Clock
You can use either of the three. You can use localstorage to save the clock end time and whenever the user refreshes the page get the value from localstorage and start you clock accordingly. Similar approach can be used with cookies. Or you can use some server side code to initialize the clock whenever your page loads the server will set start the clock accordingly. but there can be some lag as mentioned above in comments. So the best approach in my opinion, if you just want to use javascript, would be to use cookies/localstorage to save the exact time when the countdown will reach value 0. So everytime you load into the page, you can get the stored value , and get how long is missing yet and set the clock accordingly.
Some coding
Create a cookie with expiration time:
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;
}
Get a cookie:
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 "";
}
Sample of use:
function checkCookie() {
var clock = getCookie("clock");
if (clock != "") {
//You already have the cookie. Make use of it
} else {
//You still dont have the cookie, create new clock, and save cookie
//i.e.
setCookie("clock", new Date().getTime().toString(), 365);
}
}

Third party cookie to check if the browser block it by default

I want to check which browser blocks by default third party cookie.
I though to create a local file .html with a third party cookie and open it to every browser to check it will open. Is this a good option?
I plan to use this example but is it a third party cookie?
<!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 != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
This code will create a 1st party cookie - i.e. the domain of this cookie will match the domain of the page loaded.
In order to create a third party cookie you must request a resource from a different domain than the page that requests that resource. This resource could set a cookie using either javascript or HTTP header command (which is initiated by server side code like PHP).
If you are just doing your own survey to gain information about which browsers accept 3rd party cookies by default then it may be worthwhile looking at the specification for each browser to see what the official line is before going to the effort of testing.

Categories

Resources