Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am working on making premium access to my website. While doing so I want the login that had set the localStorage item as 1 to expire and get deleted after a month. I searched the web, but got confused as I am still learning JavaScript and jQuery. Can you help me out in setting expiration to the localStorage item? Here's the line of code that is setting the localStorage:
localStorage.setItem('ispremium', '1');
And my website is on Blogger platform, if that matters!
You can set the actual value as the first time user joined and the time to expire. And whenever the user opens again the website, you need to check that expiration date. But this is extremely unsecure, you shouldn't do that for sessions. Just to answer to your question, you can do the following:
const NAMESPACE = 'MY_ID';
const TIMESTAMP_MODEL = {
initial: null,
expiresOn: null
};
const TIMESTAMP = Date.now();
if (!JSON.parse(localStorage.getItem(NAMESPACE))) {
// when the user access your website for the first time, set the initial and expiresOn values:
localStorage.setItem(NAMESPACE, JSON.stringify({
initial: TIMESTAMP,
expiresOn: TIMESTAMP + 1000*60*60*24*30 // 1month in ms
}));
} else {
// then, when user access the website again, check the expiresOn, it it's value is bigger than current date
const EXPIRE_DATE = JSON.parse(localStorage.getItem(NAMESPACE)).expiresOn;
if (Date.now() > EXPIRE_DATE) {
console.log('session expired');
}
}
Normally this would be solved on the server side. The localStorage may be cleared if a user selects "clear browsing history" on some browsers. It may not be available across sessions if the user works with multiple browsers or incognito mode. Other than that someone with a bit of technical knowledge can insert the "ispremium" flag easily into his localStorage to gain access to your premium feature.
If you still want to solve this via client, you could store a timestamp instead of a boolean flag and check if the current time is still in the validity range. LocalStorage itself doesn't let you set an expiration date on entries.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a simple react app with firebase, i have my user logged in
I have a button, when is pressed i need to get the current user score in firebase ( first request) and increment this value with a random number (second request)
Get user
firebase.database().ref('user' + uid).child().once()
Update user :
firebase.database().ref('user' + uid).update({score : newValue})
Each time user press the button i made this two firebase request to get the current score and increment it
In most case user can click 150 to 600 times on the button whose can cause slowness
Do you have any suggestion to optimize my app and avoid of calling 1200 ( 2 request by 600 click) times firebase ?
why can't you try "transaction" query on the firebase.The update function takes the current state of the data as an argument and returns the new desired state you would like to write. what you have to do is just pass the key to the transaction like below
firebase.database().ref('user' + uid).child('score')
.transaction(function(current){ // current will hold current value of the key
return current + newValue ; // this return will automatically updates the new value to the firebase
});
Transaction is really good for these scenarios Follow up this link for more deets
So if you use transaction then you can reduce two queries into one.
I Hope this helps.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
As the title states, I want to send two different emails, simultaneously to two different users.
I am using JavaScript for the API.
I also would like to know how can I send delayed emails, on custom dates. Currently we can do that from the dashboard, but that allows to fix days / weeks. But what I'm looking for is to calculate the dates and add a custom date delay that can't be predefined as given in the dashboard.
Thank you.
Well the problem has been solved.
I created two separate API calls for each customer. Using switch statement and while loop
switch(customer){
while(counter > 0){
case 1:
//Make first API call
//_cio.identify
_cio.identify({
// Required attributes
id: id, // Unique id for the currently signed in user in your application.
email: yourEmail, // Email of the currently signed in user.
created_at: time, // Timestamp in your system that represents when
// the user first signed up. You'll want to send it
// as seconds since the epoch.
// Optional (these are examples. You can name attributes what you wish)
task: task,
supervisor_email: supervisorEmail, // Add any attributes you'd like to use in the email subject or body.
goal_date: date, // To use the example segments, set this to 'free' or 'premium'.
user_name: name,
supervisor_name: supervisorName,
goal_setter: isUser,
pay: pay
});
customer = 2;
break;
case 2:
//Make the second API call
break;
counter--;
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am trying to make an HTML5 and PHP based web application.The objective of the application would be to fetch the data from another PHP based website and use that data within my application.How do I do it?
The above answer is partially incorrect; PHP doesn't have access to localStorage. However, you can use cookies to achieve what you want - although you CAN use JSON with AJAX, but I think cookies are easier. Since you're very new to JavaScript, I'll show you an example.
Let's assume I'm making a very insecure login system. Let's say:
$name = "John"; //set the name to John.
Now, to let JavaScript access this name variable, we'd have to use cookies. You can use them like so:
$username = "John"; //set the name to John.
setcookie("username", $username, time()+86400);
The setcookie method take the paramaters:
setcookie(name, value, expire, path, domain);
So in our case, it sets the name to username, the value to the user's name, the expiry date from 1 hour from now (60*60*24). This cookie will expire in one day.
Now, once this is done, make sure this function is added in your scripts.
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
Please credit the original author at this topic for the code above.
Then, to get the cookie, simply do:
name = getCookie(username);
I hope I helped!
I think you can use "cookies" or "localStorage"
http://www.w3schools.com/js/js_cookies.asp
http://www.w3schools.com/html/html5_webstorage.asp
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The code below belongs to a crossrider extension I am currently attempting to develop that hopefully will sync bookmarks across browsers. This file is currently the background.js file it will first retrieve a snapshot of the bookmarks file from the local database then compare that to the current list of bookmarks and if there are any differences (either additions to the bookmarks list or subtractions) they will be be returned with the getChanges() function and then sent to the server, finally the script updates the snapshot and waits 30 seconds before restarting the process. I dont really know how to make the getChanges() function. It needs to return presumably a json object indicating both the additions and subtractions (both their titles and urls). If someone could write the code for the function that would be great. Thanks
appAPI.ready(function() {
// Poll every 30 seconds
setInterval(function() {
appAPI.db.async.get('prevBookmarks', function(value) {
// Load or initialize previous bookmarks list
var prevBookmarks = (value) ? value : {};
// Get current bookmarks
appAPI.bookmarks.getTree(function(nodes) {
// Save bookmark list for next comparison
appAPI.db.async.set('prevBookmarks', nodes);
// In your getChanges functions, traverse the bookmark trees collating
// changes and then post then to your API server using appAPI.request
var changes = getChanges(prevBookmarks, nodes);
appAPI.request.post({
url: http://yourAPIserver.com,
postData: changes,
contentType: 'application/json'
});
});
});
}, 30 * 1000);
});
Ok, you've got jQuery as one of your tags, so try this link: Compare 2 arrays which returns difference.
It returns the differences between two arrays. You'll have to perform this twice for what you're doing, once to figure out what is in current that is not in previous and vice versa. I don't know what properties are contained in your bookmarks so this simple example might not exactly suit your needs, but it might point you in the right direction.
Good luck and welcome to JavaScript!
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Ok, we run a website that has a shopping cart. Here's the scenario: a customer comes to the site and adds a product to their cart. They go to dinner and leave the item in their cart without checking out. The next day they want to buy the item. They go to the website and, without noticing it's in their cart already, attempt to add it to the cart again where they receive an error saying it's out of stock (because there is only one in stock and they have it in their cart already.) Now we lose a sale.
What I am trying to do is create 2 cookies: one that lasts 7 days (same as the cart cookie) and one for the session. The way it works is this: their first visit it creates 2 cookies: one for 7 days and one for the session. Now lets say the customer adds a product and closes their browser. The session cookie expires, leaving the 7 Day cookie there. Now when they come back, the script will check that the 7 Day Cookie is present, but not the session cookie, triggering some of my own code to be run.
The basic structure would be like this.
If 7DayCookie Exists {
If SessionCookie Exists {
End Script;
}
Else if SessionCookie Does Not Exist {
[Insert My Own Code]
}
}
Else if 7DayCookie Does not Exist {
Create SessionCookie;
Create 7DayCookie;
End Script;
}
Anybody able to make this for me? I assume it'll be a cinch for anybody that is very good with cookies and javascript.
Thanks in advance!
Final working code.
var wc = readCookie('wfwc');
var sc = readCookie('wfsc');
if (wc) {
if (sc) { }
else if (!sc) {
alert("It works.");
}
}
else if (!wc) {
createCookie('wfwc','week',7);
createCookie('wfsc','session',0);
}
I highly recommend the cookie functions from Peter Paul Koch's quirksmode. The 3 functions you need are createCookie, eraseCookie, and readCookie.
For the session cookie, you'll want to create a cookie that contains no "expires" header. for the 7 day cookie, you'll want to create a cookie that expires in 7 days.
Then, in javascript, you can do something like:
theme = readCookie("theme");
// if a cookie called "theme" isn't present, initialize.
if (!theme) {
theme = "sky.json";
}
I use PPK's scripts myself, I did change the == to === to avoid type coercion in the functions, although it's not strictly necessary.