How to store multiple document.referer value in sessionStorage? - javascript

How to store multiple document.referer value in sessionStorage?
For example:
you visit www.stackoverflow.com
-> current sessionStorage (value) is www.stackoverflow.com using JS document.referer
-> then you click one of the link on stackoverflow.com, example you click stackoverflow questions
page www.stackoverflow.com/questions. your current sessionStorage is now www.stackoverflow.com/questions
-> and then you click one of the individual questions link www.stackoverflow.com/questions/howtofixthis/
How do we store the previous document.referer values in sessionStorage which is accessable in the fourth page
example in stackoverflow.com/questions/howtofixthis/ you click one users with link www.stackoverflow.com/user/iamcoder
in current page the previous the sessionStorage values should be accessable, the values are:
1st origin value = www.stackoverflow.com
2nd www.stackoverflow.com/questions
3rd www.stackoverflow.com/questions.com/howtofixthis/
4th www.stackoverflow.com/user/iamcoder
The purpose of using sessionStorage is to store visited pages url in current session and accessible through multiple external pages.
So far this I came up this code but doesn't store previous links at origin.
<script>
var s_origin = document.referrer;
var on_session = sessionStorage.setItem('origin', s_origin)
var data = sessionStorage.getItem('origin');
console.log('session origin ' + data)
</script>

You need to read the current value in session storage and append the new one.
function appendReferrer(value){
if(value){
var referrers = JSON.parse(sessionStorage.getItem('origin') || null) || [];
referrers.push(value);
sessionStorage.setItem('origin',JSON.stringify(referrers));
}
}
function getReferrers(){
return JSON.parse(sessionStorage.getItem('origin')) || [];
}
Usage:
//Append a new Item
appendReferrer("stackoverflow.com");
//Read all referrers
var referrers = getReferrers();
console.log(referrers);

Related

Using Promise for a function that is not called by JavaScript

I am using Google Sign-In and have the following problem:
sessionStorage.getItem('userEntity') returns null when I close the browser and open it again. It does not return null if I just reload the page.
The session will be set in this function:
// Signing in
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
// Store the entity object in sessionStorage where it will be accessible from all pages
let userEntity = {};
userEntity.id = profile.getId();
userEntity.name = profile.getName();
userEntity.img = profile.getImageUrl();
userEntity.email = profile.getImageUrl();
sessionStorage.setItem('userEntity',JSON.stringify(userEntity));
userIsLoggedOut.style.display = 'none';
userIsLoggedIn.style.display = 'flex';
document.querySelector('.user-img').setAttribute('src', userEntity.img);
}
I do not run this function in JavaScript. The following HTML will make it run:
<div class="g-signin2" data-onsuccess="onSignIn"></div>
Even if I put console.log(sessionStorage.getItem('userEntity')) after the function or on the bottom of my JavaScript, it still returns null.
I guess a solution would be using Promise but how can I use it if I don't run the function onSignIn() in JavaScript?
The data stored in SessionStorage are deleted when you close the tab or the browser, more details below:
https://www.w3schools.com/jsref/prop_win_sessionstorage.asp
You can use localStorage instead to keep the data in the browser even if you close the tab or the browser, so change the following line:
sessionStorage.setItem('userEntity',JSON.stringify(userEntity));
by
localStorage.setItem('userEntity',JSON.stringify(userEntity));
But you have to take care about the security of the informations stored in the localStorage, you can deal with secure cookies if you need to store secure data client side.
You can copy item from sessionStorage to localStorage:
localStorage.setItem('userEntity', sessionStorage.getItem('userEntity'));
It will be persistent, so you can use it anytime:
localStorage.getItem('userEntity');

How do I delete one item from an array with chrome.storage.sync.remove?

I'm building a Chrome browser extension which includes a feature that lets users save urls. I used chrome.storage.sync to create this feature and didn't encounter any issues.
However, I also need to let users delete urls they've already saved. I created a text input box where they can enter a single url they want to delete (i.e. "www.url.com"). I want to convert this input into a string and use it to remove a matching string from Chrome storage when the user presses a button.
I thought the chrome.storage documentation specifies that chrome.storage.sync.remove can be used to remove a string from a stored array, but I can't get it to work. Here's my code:
function removeUrl() {
var theUrl = document.getElementById('url-input').value;
chrome.storage.sync.get(null, function(result, error) {
// Checks if the array (urlList) exists:
if ('urlList' in result) {
var theList = result['urlList'];
// Checks if the url that will be deleted is in the array:
if (theList.includes(theUrl)) {
chrome.storage.sync.remove(theUrl);
chrome.runtime.reload();
}
}
// Error handling goes here
});
}
This code doesn't throw any errors, but it doesn't remove the url from the array either.
Please note that I only want to delete 1 url at a time, there are no duplicate urls in the array, and I am not using any libraries like jQuery. What am I doing wrong?
You cannot do it this way, because chrome.storage is a key-value storage.
In your particular example, you are trying to remove from storage one element of the array, but storage contains only key with array.
The best solution here will be just removing this value from the array and set the array to the chrome.storage again.
var theList = result['urlList'];
// Checks if the url that will be deleted is in the array:
if (theList.includes(theUrl)) {
// create a new array without url
var newUrlList = arr.filter(function(item) {
return item !== theUrl;
});
// set new url list to the storage
chrome.storage.sync.set({ 'urlList': newUrlList });
chrome.runtime.reload();
}

about local storage.getItem()

I'm a new learner for API, and I have a quesion about local storage. This is a code example from my javascript book:
if (Modernizr.localstorage) {
var txtUsername = document.getElementById('username');
var txtAnswer = document.getElementById('answer');
txtUsername.value = localStorage.getItem('username');
txtAnswer.value = localStorage.getItem('answer');
txtUsername.addEventListener('input', function () {
localStorage.setItem('username', txtUsername.value);
}, false);
txtAnswer.addEventListener('input', function () {
localStorage.setItem('answer', txtAnswer.value); }, false);
}
}
I want to ask why should we "localStorage.getItem()" part? Cause I think if user type their username, then we can get their names just from the variable "txtUsername" cause I thought it should be setItem first and then getItem. Thank you!
Local storage is used to store small amounts of data on the client side. What does your code ?!
For example: A user visited the site for the first time and complete the inputs, , the data stored in the local store. The user closed the browser. The next day he again went to the site to fill out the form again, and its data is already filled. Conveniently!
Also we can use local storage as js object
txtUsername.value = localStorage.getItem('username');
txtUsername.value = localStorage.username;
txtUsername.value = localStorage['username'];
The thing is, it works just as you said.
It's just, when person types data in the textbox he uses setItem - that what 'input' eventListener used for
Think of LocalStorage as of really light database that keeps data even when user closes the page
But since it can store data when page is closed, you want to show the content of it in the textbox - and that's why author uses 'getItem' on start

Storing data from elements before a refresh

I have a web page with 3 elements where a user will enter a text value and then press a button. On submit, it will process and return some values to be populated in a table.
This part works fine.
Now if the user refreshes the page, all the data is gone and the 3 elements and the table looks empty.
I would like to do this. Catch the refresh event and store the 3 user entered values in a local storage and when the page is loading back up, I will send this back to the controller to populate the tables again.
Is this possible to do? I am pretty new to web development and am running out of ideas.
This is what I tried. And this doesn't work.
window.onbeforeunload = function() {
localStorage.setItem(name, $('#name_field').val());
localStorage.setItem(id, $('#id_field').val());
localStorage.setItem(pw, $('#pw_field').val());
alert("am here")
}
window.onload = function() {
var name= localStorage.getItem(name);
if (name != null) $('#name_field').val(name);
var id= localStorage.getItem(id);
if (id!= null) $('#id_field').val(id);
var pw= localStorage.getItem(pw);
if (pw!= null) $('#pw_field').val(pw);
}
I could never get the alert in window.onbeforeunload function to pop up.
You can store it everytime on the local storage(or event session storage, which I think its better in your case). Then everytime you look after that value on the storage. In case of any value found, you send it to the controller.
If it was me I would do as I said above, save your data into the sessionStorage(what means that the data will be lost if user closes the tab/browser):
var saveData = function()
{
var data =
{
id: $("#id_field").val(),
name: $("#name_field").val(),
pw: $("#pw_field").val()
};
sessionStorage.setItem("formValues", JSON.stringify(data));
}
Idk if your post is async or not. If its async, you can call that function on your successCallback, if it isn't async, call it on the submit event.
Then at ready event, you can read that data:
$(document).ready(function()
{
var data = sessionStorage.getItem("formValues");
// Check if there is any user data already saved
if (data)
{
data = JSON.parse(sessionStorage.getItem("formValues"));
$("#id_field").val(data.id);
$("#name_field").val(data.name);
$("#pw_field").val(data.pw);
}
});
I prefer to store a group of data in an object into a single key on the storage, that is why I use JSON to stringify and parse an object, because storage only accepts string types.
A simple advise: Don't - ever - store passwords, let the user type it. For security reasons.

Remembering search parameters

I am trying to make a small website with search filters (textbox and checkboxes). I have searched around and seen that the way to remember the past search filters ONLY AFTER refresh is using session storage.
However, the problem is that, even when the user browses around the website and comes back to the search page, he/she would still see the past search filters. I want to reset the search filters when the user is coming from a different page.
I'm thinking and searching around as to how to remove these variables stored in the session storage after the user leaves the page and only keeping it when the user refreshes.
My current code goes like this :
var selectedCompanies = new Array;
var selectedCategories = new Array;
var searchWord = "";
if(sessionStorage.getItem('selectedCompanies') != null){
selectedCompanies = JSON.parse(sessionStorage.getItem('selectedCompanies'));
alert("NOT NULL!");
//loop to recheck checkboxes
}
if(sessionStorage.getItem('selectedCategories') != null){
selectedCategories = JSON.parse(sessionStorage.getItem('selectedCategories'));
//loop to recheck checkboxes
}
if(sessionStorage.getItem('searchWord') != null){
searchWord = sessionStorage.getItem('searchWord');
$('#filter-searchbar').val(searchWord);
}
Please help as to how can I delete the variables inside the session storage after the user leaves the search page. Thanks!
Add the following code in a common JavaScript file. Reference this file on all pages except the search page:
sessionStorage.removeItem('selectedCompanies');
sessionStorage.removeItem('selectedCategories');
sessionStorage.removeItem('searchWord');
This will clear the search parameters on all other pages but allow the data to persist on the search page.

Categories