Save apikey between sessions - javascript

I'm making a little client-side web app for MagicCardMarket.eu. It's just javascript and html. The user has to log in using his username and apikey, though I was wondering what's the best way to save these between sessions?
It's the first time I make this kind of web app. It's also the first time I use anything like this apikey, so I wasn't sure what to Google.
Thanks!

You can use sessionStorage.
sessionStorage.setItem('key','value');
var value = sessionStorage.getItem('key');
So what is it?
This is a global object (sessionStorage) that maintains a storage area
that's available for the duration of the page session. A page session
lasts for as long as the browser is open and survives over page
reloads and restores. Opening a page in a new tab or window will cause
a new session to be initiated.

use session storage. It stores values as key, value pairs.
To set the value to session use
sessionStorage.name = "Use Name";
sessionStorage.APIKey = "Use APIKey";
To Get the values from session storage:
var name = sessionStorage.name;
var APIKey = sessionStorage.APIKey;
Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!

Related

Return Paths From Session

Using Vanilla Javascript, I need to write a script that console logs an array of every unique page path visited during a browser session.
I am trying to do local storage and set the key with the current pathname. The part that I am getting suck on is pushing another value to that key in local storage.
So far I've gotten
localStorage.setItem('path', window.location.pathname);
But when I re-run that code it overwrites what I had already saved.
Where am I going wrong?
You will need to use JSON stringify/parse for saving and accessing the data.
_saved = localStorage.getItem('path') || "[]";
_saved = JSON.parse(_saved)
_saved.push(window.location.href)
localStorage.setItem('path',JSON.stringify(_saved))
console.log(JSON.parse(localStorage.getItem('path')))

my code storage data in local storage on a website but when i navigate through the pages and register a new user the old user are deleted

var userInfo = [];
var myCostum;
//documentgetElementById("registerForm");
document.getElementById("registerForm").addEventListener("click", function ()
{
//var register = document.querySelector('#registerForm');
var name = document.querySelector('#fN').value;
var lastN = document.querySelector('#lN').value;
var userName = document.querySelector('#uN').value;
var passwrd = document.querySelector('#pS').value;
userInfo.push([name,lastN,userName,passwrd]);
localStorage.setItem("myCostum", JSON.stringify(userInfo));
});
I am using separate files for j, my website has a navigation bar with home,register,login,about me and shopping car. this code works fine if i register more than one user, i can see the users in the local storage on all pages and i can even sign in. the problem is when i go to register again and register a new user the users that i reister before are deleted and replaced by the new user. also if i go to home page i can an error (Uncaught TypeError: Cannot read property 'addEventListener' of null
at even-listener.js:9). i just do not had idea why register page seems to work but the rest not. I had another code using onclick in html but the same it does not give any error in any page but the users gone when i register new one after navigating through my pages. this is the first time using localStorage and i do not can i do or if it is normal. i am stack and i need to keep adding more code but i want to solve this problem first.
Lots of things going on here, but let me start from the basics.
1st never use local storage for sensitive information such as usernames and passwords. There's a lot of sites that copy local storages and send it to malicious people.
2nd you could in theory use session storage limited to the tab, but you still could be under the danger of xss.
3rd when the browser closes, all your data will be lost from the local storage anyway
As for your code. Your user info, should not be initiated as empty. You must get the previous value from local storage and push to it. Otherwise you are just overriding the previous value.
var userInfo = JSON.parse(localStorage.getItem('myCustom'));

Saving $("#some-id") in a variable to access it later

I want to save selected jQuery object to some variable and to be able to access it after navigating to some other page, since after reloading it disappears.
Here is what I am trying to do:
var active_accordion;
$(function() {
active_accordion.prop('checked', true);
$('.active-evm a').on('click', function() {
active_accordion = $('#section-1');
alert(active_accordion);
});
}
Whenever link is clicked I save $('#section-1') to active_accordion, and after navigating to other page I try to change property checked to true.
Of course it doesn't work, because active_accordion disappears after navigation. So where can I store it?
save to local storage,
the example,
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
You can store it in session storage sessionStorage.
sessionStorage.setItem("itemKey", value);
Edit: sessionStorage items persist as long as the browser session is active.
If you want to persist your items even if you restart your browser, you can use localStorage, but be careful with its usage as the data tends to get stale if you do not use it properly.
There are lot of ways you can do this
1) Store those in session
2) Store it on cookies
Note :when using Cookies be careful, don't put too much in them (I
think there is a limit at 4kb).
3) you can store it in local storage in your system
example : save values to a file
4) you can store it on database
5) Or just use PersistJS
PersistJS is good choice because you can store large objects like
window objects aswell
6) You can use the help of WebStorage
7)you can use window.name
it is originated before localStorage/sessionStorage, you can store information in the window.name property:
window.name = "stringvalue"
It can only store strings
, so if you want to save an object you'll have to stringify it just like the above localStorage example:
window.name = JSON.stringify({ object });

Uniquely identify a duplicated Chrome tab

I am currently using window.sessionStorage to store a uniquely generated session ID. This ID is passed to all ajax calls to the server and persists across page navigation and reloads.
This seems to work perfectly for my target browsers, with one caveat: the duplicate tab functionality in Chrome.
Duplicating the tab copies the session storage to the new tab. When the new tab loads and communicates with the server, it now has the same "unique" identifier as the duplicated target tab.
Are there any ways that I can distinguish between the two duplicated tabs?
Or are they truly duplicates and no information is different between the two?
Nothing persists after the tab/window is closed, so even a simple numeric tab id or anything would work as long as it is unique for that current instance.
A variant of this worked for me:
https://stackoverflow.com/a/60164111/13375384
The trick is to only put the ID in session storage for the brief period of time when the tab is refreshing
In my TypeScript project, the solution looked like this:
const tabIdKey = "tabIdStorageKey"
const initTabId = (): string => {
const id = sessionStorage.getItem(tabIdKey)
if (id) {
sessionStorage.removeItem(tabIdKey)
return id
}
return uuid()
}
const tabId = initTabId()
window.addEventListener("beforeunload", () => {
sessionStorage.setItem(tabIdKey, tabId)
})
Session storage is on the browser level, and not on the tab level. See https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage .
The only method I know of to identify a tab is to pass a paramater at the end of each URL (and even so you would need to use JavaScript to prevent open in new Tab).
Other methods would be unbearable, such as embedding an iframe in the app (and storing the identifier in the parent), but possible.
In short, you should rephrase you question to simply identifying a tab, and you will nevertheless not find an answer.
My eventual solution to this was to generate a unique ID on the server side which gets stored in the server session and passed back to be stored in sessionStorage. I also have another value (let's call it FOO) that is set on the client side and stored.
Pretend it looks like this in a map:
{
"unique_id" : "ABC123",
"FOO" : "some value"
}
I send the values up to the server with every ajax request.
On page load, I check to see if I already have the unique_id, FOO pair in sessionStorage and load them. Any time the value of FOO changes, it will get compared with the server pair. If it has a different value then I store the new value for FOO under a new unique ID and hand it back to the client.
This doesn't 100% solve the problem, but it does make sure that FOO, which represents some persistent state, is never used incorrectly after tab duplication.
The tab that originally had had the unique_id, FOO pair will continue to have that pair while the duplicated tab will have a new pair.
Technically, until the value of FOO changes the two tabs share the same unique_id, but as long as unique_id gets reassigned when FOO changes, they won't overwrite each other's state within the server session.

Javascript > form results to "remember" user > avoid showing form twice

I have a java script form in a website, that outputs some results -a silly simple mathematical operation or subtraction of dates.
I need these results to "remember" the visit so the div and the results
show when the user re-loads the page.
How can I achieve this?? It's my first time with facing a situation like this...
Note: its not a logged user!! but a non-logged visit..
http://goo.gl/OHQmpb
You can use localStorage.
Store the values in it by specifiying a key:
localStorage.setItem('key','value');
And, you can get the value by:
var value = localStorage.getItem('key');
HTML5 Web storage is the best option in your case.
Exact definition:
So what is HTML5 Storage? Simply put, it’s a way for web pages to
store named key/value pairs locally, within the client web browser.
Like cookies, this data persists even after you navigate away from the
web site, close your browser tab, exit your browser, or what have you.
Unlike cookies, this data is never transmitted to the remote web
server (unless you go out of your way to send it manually).
With HTML5, web pages can store data locally within the user's browser.
// Store it in object
localStorage.setItem("form attributes", "form values");
// Retrieve from object
localStorage.getItem("form attributes");
HTML5 Local Storage aka Web Storage can store values without maintaining a server side session. See this example:
function calculate(){
return 'some value';
}
window.onload = function(){
// submit handler for the form, store in local storage
document.getElementById("myform").onsubmit = function(){
localStorage.setItem('calcResult', calculate());
return false;
};
// load the value if present
var result = localStorage.getItem('calcResult');
if(result != null){
// show in div
document.getElementById("mydiv").innerHTML = result;
}
}

Categories

Resources