Generator Features
18 min read
Persist and Copy History
Persist and Copy History
Make the working history survive reloads and let each history row use the copy function you already built.
1. Save after an update
At the end of addHistory():
try {
localStorage.setItem("passwordHistory", JSON.stringify(history));
} catch (error) {
// Keep the in-memory version working if storage is unavailable.
}
2. Load on startup
Replace the initial empty state with a safe read:
let history = [];
try {
history = JSON.parse(localStorage.getItem("passwordHistory") || "[]");
} catch (error) {
history = [];
}
if (!Array.isArray(history)) history = [];
Call renderHistory() once during startup so saved values appear immediately.
3. Reuse copyText() in each row
Inside the history loop, create the prepared small-copy button:
const button = document.createElement("button");
button.className = "small-copy";
button.type = "button";
button.textContent = "▣";
button.addEventListener("click", () => copyText(password));
Append it beside the password:
row.append(code, button);
4. Clear the history
Use the existing clearHistory reference:
clearHistory.addEventListener("click", () => {
history = [];
localStorage.removeItem("passwordHistory");
renderHistory();
});
Test
Generate several values, reload, copy one from history, then clear all. Reload again and confirm the cleared state remains.
Checkpoint
History is now unique, limited to five, persistent, individually copyable, and clearable.