I have the following shorted code to easier demonstrate my problem:
<script>
function change() {
document.getElementById('change').innerHTML = "Done!";
}
</script>
<div id="change" onclick="change();">Change me!</div>
Let's say the files name is test.html
.
When clicking on Change me!
the string will get changed to Done!
.
Safari, Firefox: When clicking on the browser back button and then the browser forward button to go back to my test.html
, it's showing Done!
. This is what I expect!
Doing the same with other browsers (Chrome, Vivaldi, Min, Opera), I'm getting Change me!
instead of Done!
.
Safari and Firefox seem to keep the Javascript changes while other browsers load the page without the Javascript changes, when using back and forward buttons.
Is there a way to reach the same behavior for other browser as it's working in Safari and Firefox?
You can look at using Window.sessionStorage
or Window.localStorage
of your browser to store and retrieve the state for the cases where back button/forward buttons are used
<script>
window.addEventListener("load", function(event) {
setHTML();
})
function setHTML() {
document.getElementById('change').innerHTML = window.sessionStorage.getItem("state")||"NOT IN FAVORITES";
}
function addToFavorites() {
window.sessionStorage.setItem("state", "Done");
document.getElementById('change').innerHTML = window.sessionStorage.getItem("state");
}
</script>
<div id="change" onclick="addToFavorites();">Change me!</div>