I understand, you want to avoid losing the data as long as you do not complete the form, accidentally close the extension popup, is this?
You can use localStorage
, for example:
localStorage.setItem('meuForm', '... dados do form ...');
And load the data like this:
localStorage.getItem('meuForm');
Of course this will not do anything automatically, you have to do a function that reads all inputs and associates each with a key type in localStorage
, you can use JSON.stringify
to save and JSON.parse
to reload , or you can use multiple setItem
, for example:
<form>
<input type="text" name="nome">
<input type="text" name="sobrenome">
<select name="sexo">
<option name="">Selecione...</option>
<option name="femi">Feminio</option>
<option name="masc">Masculino</option>
</select>
<button>Enviar</button>
</form>
Javascript would look like this:
(function() {
var campos;
//Detecta alterações nos inputs, textareas e selects
function eventosRascunho() {
campos = document.querySelectorAll("#meuForm input, #meuForm textarea, #meuForm select");
for (var i = campos.length - 1; i >= 0; i--) {
if (campos[i].tagName === "SELECT") {
campos[i].addEventListener("change", salvaRascunho);
} else {
campos[i].addEventListener("input", salvaRascunho);
campos[i].addEventListener("keyup", salvaRascunho);
campos[i].addEventListener("paste", salvaRascunho);
campos[i].addEventListener("cut", salvaRascunho);
}
}
}
//Salva rascunho no localStorage
function salvaRascunho() {
for (var i = campos.length - 1; i >= 0; i--) {
var nameAttr = campos[i].getAttribute("name");
if (nameAttr) {
localStorage.setItem(nameAttr, campos[i].value);
}
}
}
//Limpa rascunho no localStorage
function limparRascunho() {
for (var i = campos.length - 1; i >= 0; i--) {
var nameAttr = campos[i].getAttribute("name");
if (nameAttr) {
localStorage.removeItem(nameAttr);
}
}
}
//Restaura rascunho para os <select>
function restauraHtmlSelect(options, valor) {
for (var i = options.length - 1; i >= 0; i--) {
if (options[i].value === valor) {
options[i].selected = true;
break;
}
}
}
//Carrega rascunho se existir
function carregarRascunho() {
//Verifica se os rascunhos estão vazios
if (localStorage.length === 0) {
return;
}
for (var i = campos.length - 1; i >= 0; i--) {
var dados = localStorage.getItem(campos[i].getAttribute("name"));
if (!dados) {
continue;
}
if (campos[i].tagName === "SELECT") {
restauraHtmlSelect(campos[i].querySelectorAll("option"));
} else {
campos[i].value = dados;
}
}
}
window.onload = function () {
eventosRascunho();
};
})();
After sending the form successfully use the limparRascunho();
function to erase the data and prevent the form from restoring them.