Can we temporarily store data on browser ? For an example , i have page A and page B
On page A(a.html) , i would want to temporarily store text "Helloworld" on button click
function a(){
return "helloWorld"
}
function changePage(){
a()
window.location(b.html)
}
On page B(B.html), i would want then to capture "Helloworld" on page A and print it on page b.
console.log(a())
I read on postMessage but based on my understanding , this only works on 2 page thats loaded on a single page on cross-domain workaround.
You can use the browser’s local-storage capabilities: localStorage. It helps to store data on the browser as strings.
To store data:
localStorage.setItem('foo', 'helloWorld');
To get the saved data:
localStorage.getItem('foo');// return 'helloWorld'
I think sessionStorage fits your purpose. But mind that the data is removed when the user closes the browser - if you don't want that, simply replace sessionStorage with localStorage. But as long as you don't need the data to be persistent across restarts you should rather use sessionStorage to not fill up the users disk:
window.addEventListener("load", function() { // this is executed when the site is loaded
inputElement = document.getElementById("dataInput");
inputElement.addEventListener("input", function() { // and this whenever the user changes the contents of dataInput
window.sessionStorage.setItem("dataInput", inputElement.value());
});
});
<input id="dataInput" type="text" placeholder="Enter your data">
window.addEventListener("load", function() {
outputElement = document.getElementById("dataOutput");
outputElement.setText(window.sessionStorage.getItem("dataInput"));
});
<p id="dataOutput">The data should appear here</p>