I have an application which open several windows (with javascript) in the same domain.
I would like to share some javascript objects between these windows (an object which contains some configurations for example).
Is it possible to do this in javascript and how to do this ?
Thanks.
There are 2 possibilities: local storage and session storage
The session storage stores value for duration of the session, the value gets deleted when browser is closed and re-opened.
// Store value
sessionStorage.setItem('key', 'value');
//or
sessionStorage['key'] = value;
// Retrieve value
alert(sessionStorage.getItem('key'));
The local storage stores value beyond the duration of the session, the value can be retrievedeven after closing and re-opening the browser.
// Store value
localStorage.setItem('key', 'value');
//or
localStorage['key'] = value;
// Retrieve value
alert(localStorage.getItem('key'));
Use localStorage along with JSON to store your objects as strings:
Setting:
window.localStorage.setItem('yourKey', JSON.stringify(yourObject));
Getting:
var yourObject = JSON.parse(window.localStorage.getItem('yourKey'));
the localStorage data will be shared across all of your pages as long as they exist in the same domain.
If you used window.open() to create the second window, window.opener in the second window might give you access to the first window. See MDN.
Related
Using Vanilla Javascript, I need to write a script that console logs an array of every unique page path visited during a browser session.
Here is my starting point:
function() {
var pageUrl = window.location.href;
return pageUrl;
}
Session storage is a small (often 5MB) area of space on the user's computer which you can write to. When the session ends (e.g. the browser is closed) the session storage is cleared, and in this way it is different to local storage.
Lets imagine we keep a list of pages around in the session storage. Items are stored in session storage as key / value pairs of strings, and as such we need a key (think of this as a variable name that persists across pages) and a value. Initially, you may think that we can just store an array in such a data store, but the session storage API can only store strings. Therefore, we'll need to convert our array back and forward between a JSON representation as we use it.
When you need to get the list of pages, just grab it from session storage (it's important you get a fresh copy each time, as this accounts for e.g. visits in another tab while the current one remained open). You can do this like so:
function getListOfPages() {
let pages = [];
// If not null, then we have previously stored something --- load that in
if (sessionStorage.getItem("visited") != null) {
// Get the item, and convert it from a JSON string to an actual array
pages = JSON.parse(sessionStorage.getItem("visited"));
}
return pages;
}
And when we need to add a new page, we can then just update that list in storage. For example, we could use a function such as this one:
function addPageToList() {
// Use the get function we made before to get the most up-to-date list of pages
let pages = getListOfPages();
// Add the current page to the list
pages.push(window.location.href);
// Override the value stored in session storage, or add it if no such value exists
sessionStorage.setItem("visited", JSON.stringify(pages));
}
In your post, you mention you want to console.log all of the unique paths. To do this, you could replace the array in all of the above code with a set, as sets cannot contain duplicate items. However, do note that you can't convert a set to JSON (at least not directly / intuitively), so you may be best advised to do this step after obtaining the list of pages, e.g:
console.log(new Set(getListOfPages()));
Wrapping in a set will remove all of the duplicate items in the array, and then you can print out the set to the console as normal.
I have two html documents, and I want them to share a variable and its value.
In lieu of 'truly global' variables in JavaScript, I've tried employing Web API Storage:
var number = parseInt(localStorage.setItem('num',0));
Storage is always a string, so I try parsing into an integer seemingly incorrectly (rather than showing up as 0 in my program, it shows up as 'NaN'). I can only assume that my syntax's wrong?
I want this variable to be increaseable (+1 every time the user clicks on something) but have not yet figured this out. I then want to retrieve its value in the second html document. But due to the initial misstep in attempting to parse the storage value I cannot yet attempt these methods.
It doesn't work like that because localStorage.setItem returns undefined. The way to do it would be:
// define variable
var num = 0;
// set to storage
localStorage.setItem('num', num);
// get from storage
num = parseInt(localStorage.getItem('num'));
// write-back incremented
localStorage.setItem('num', num + 1);
localStorage.setItem stores the value but doesn't return anything - or in other words returns undefined. Trying to parse undefined as a number returns NaN.
Note that localStorage does not work across files when viewing files in your browser from file://, you'll need to run a minimal server to test your code.
I have seen many examples for fetching the already stored data but didn't get any example for fetching the stored values.
You can access localStorage through browser.executeScript() this way:
Get value
var value = browser.executeScript("return window.localStorage.getItem('myKey');");
Set value
browser.executeScript("window.localStorage.setItem('myKey', 'myValue');");
I am running an old version of Angular - I have an object within my localStorage and I am trying to retrieve a single item from the object (rather than the whole the thing..)
var email = localStorage.user;
However the output of the localStorage.user variable is much longer (see below)- how would I retrieve the email address in this case 'bob#abc.com'?
{"firstname":"Bob","lastname":"Dole","id":"2000001999","accountId":"15","email":"bob#abc.com","instances":[{"name":"Test"}]}"
LocalStorage values are always stored as strings. In order to refer to the email in the object, we need to convert it to a JSON. We can do that by parsing the string using JSON.parse() method like below :
var email = JSON.parse(localstorage.user).email
You have Json structure not JS object, so parse it 1st
var email = JSON.parse(localStorage.user).email;
Using html5 local storage we can store data, add expire time by using cookies and sessions. https://stackoverflow.com/a/41385990/6554634 go through that, gives a lot of explanation
I am trying to send an information from one page to another through javascript file
the information will only contain a value of single variable.
how to accomplish this?I dont want to send it through query string as the value will be visible in the URL.
is there any other way?
You could save your data in LocalStorage and retrieve it on the other page.
localStorage.yourData = '{ test:"data" }';
console.log(localStorage['yourData']);
You have a few options to do that.
Depending on what browser is used, using localStorage is an option
//localStorage ONLY stores flat key:value pairs and can't contain Objects
localStorage.myString = "hello world";
localStorage.myObject = JSON.stringify({ foo: "bar" });
//Reading back the values is simple aswell
var myString = localStorage.myString;
var myObject = JSON.parse(localStorage.myObject);
Another method would be using a hash or query string. For example, you could redirect to www.yourdomain.com/your/path?myValue=1234
And then parse that by reading the search value from window.location.search (Will return ?myValue=1234 in that case) and splitting it on =:
var myValue = window.location.search.split("=")[1];
Another option is using hashes, similar to query params. Or even cookies.
BUT, all these methods will expose the value to the user, so if he wants to get that value, he will be able to!
At first, as other answers, use localStorage or sessionStorage to store global data.
Otherwise, you can add an event listener to detect the change of the storage value in your target page as follow:
window.addEventListener('storage', (e) => console.log(e.key, e.oldValue, e.newValue))
See: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Responding_to_storage_changes_with_the_StorageEvent