Problem
I’m making a static webpage that takes some values as inputs & calculates some stuff, and more often than not, I end up reusing the same inputs from one session to the next.
Firefox has been filling my <input>
s with the data from the previous session, but I’d like a way to know if Firefox had cached data or not :
- if there was cached data that is being fed to the form, I want to accept it
- if there wasn’t, I’d like to trigger a reset to my default form data
What i’ve tried
I’ve tried a very basic use of onload
:
<body
style="[...]"
onload="init()"
>
with init being a function that tests if my inputs have a value
function init() {
if (document.getElementById('myInputA').value &&
document.getElementById('myInputA').value !== emptyValueA) {
// use the value that was "stored" for A
}
else if (document.getElementById('myInputB').value &&
document.getElementById('myInputB').value !== emptyValueB) {
// use the value that was "stored" for B, in a different way
}
else {
// reset inputs to their base value
}
}
Except this fails miserably, as input()
gets triggered at a time when the input elements have their base value (understand their value=...
declared in the html element) at that time.
And then later on, I see the oninput
method for my inputs get triggered by Firefox inserting the cached values.
Note : Firefox seems to insert those values sequentially, as I can track the oninput
s being triggered one by one.
I have not found an event that would happen after that (checked https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState, the “load” event page & related).
Solutions ?
Since Firefox inserting the data into my inputs triggers their oninput
methods, I could probably just set the oninput
method to a special function for the first time that would be in charge of the initialization, but then I’d still need a way to detect never being triggered, which doesn’t fully solve the problem, unless I use some timeouts & arbitrarily decide a window during which no human would input anything.
I am interested in knowing if other browsers do this kind of thing, how they do it (same page lifecycle ?) & how I could work with this behavior in said other browsers.