I have 2 pages between which I switch. I got some input field on first page:
<input type="date" id="dateFrom" />
And I have a button on the second page:
<button action="action" onclick="window.history.go(-1); return false;" type="submit" value="Cancel"
>Back</button>
Task: set the date on the first page, go to the second and click on the "Back" button to return to the first page with the same date. Visually, everything works as it should - I install 2023-01-06 in the DateFrom and go to the second page. I press the Back button and return to the first page where the date From field is 2023-01-06. However , the following output occurs in the console:
document.addEventListener("DOMContentLoaded", function (event) {
console.log(document.getElementById("dateFrom"))
console.log(document.getElementById("dateFrom").value)
});
outputs:
input#dateFrom
validity: ValidityState {valueMissing: false, typeMismatch: false, patternMismatch: false, tooLong: false, tooShort: false, …}
value : "2023-01-06"
valueAsDate: Fri Jan 06 2023 03:00:00
empty
empty - literally an empty space ...
I'm literally confused, why is this happening? How do I access the date From value after returning from the previous page? Thanks for the answers.
CodePudding user response:
TL;DR: Use the Web Storage API to persist data between pages.
Not recommended: (Chrome and Firefox) Use the "load"
event on window
instead of "DOMContentLoaded"
on document
.
window.addEventListener("load", function () {
console.log(document.getElementById("dateFrom"))
console.log(document.getElementById("dateFrom").value)
});
In modern browsers, when doing a backwards navigation, the browser tries its best to restore the state of the previous page from cache. This usually includes restoring user input, timers, pending promises, etc..
However, restoring page state from cache isn't standardized, so the exact behavior in browsers can vary greatly from each other. For instance, Chrome, Firefox, and Safari will all cache the state of the date input, but your code will actually properly output the date in Firefox, meanwhile, in Safari the "DOMContentLoaded"
event doesn't even get fired on backwards navigation.
As a result, you should NOT rely on the cache as a way of preserving or restoring state locally between page navigations. To do so correctly, look into the Web Storage API. You should listen for "input"
events and update the storage, accordingly.
But to answer your question on what's happening in Chrome, its particular cache restoration strategy seems to only restore form values sometime after "DOMContentLoaded"
. In other words, when your "DOMContentLoaded"
event handler executes, the browser hasn't actually restored the data from the cache yet, therefore the input element has its default value, an empty string. However, it seems to restore it by the time the "load'
event fires, so you can add a listener for that instead.