API da ponte JavaScript
Tarefas em segundo plano
Trabalho que continua depois que o app é fechado: um salvamento automático durável, uma sincronização periódica.
workCancel ponte#
window.WebToApk.workCancel(id: String)
Nenhuma permissão necessária; os resultados ecoam como `appmint:work` / window.onAppMintWork.
Descrito pelo seu grupo, Tarefas em segundo plano (WorkManager): salvamento automático durável + sincronização nativa periódica, e não isoladamente.
Exemplo
Cancela uma tarefa em segundo plano (única ou repetida) pelo id e apaga a requisição salva dela.
Retorna: nada diretamente. O evento appmint:work (e window.onAppMintWork) responde { id, status: 'cancelled' }. Requer: nada.
function stopSync() {
if (!(window.WebToApk && window.WebToApk.workCancel)) return;
WebToApk.workCancel('sync');
}
window.addEventListener('appmint:work', function (e) {
if (e.detail.id === 'sync' && e.detail.status === 'cancelled') {
document.getElementById('sync-status').textContent = 'Background sync is off';
}
});Descarte um rascunho: cancele o salvamento automático dele que ainda não foi enviado e depois limpe o editor quando o Android confirmar:
function discardDraft() {
if (!(window.WebToApk && window.WebToApk.workCancel)) { clearEditor(); return; }
function onWork(e) {
if (e.detail.id !== 'autosave' || e.detail.status !== 'cancelled') return;
window.removeEventListener('appmint:work', onWork);
clearEditor();
}
window.addEventListener('appmint:work', onWork);
WebToApk.workCancel('autosave');
}Ao sair da conta, cancele todas as tarefas deste app, usando os ids que workList informa:
function cancelAllJobs() {
if (!(window.WebToApk && window.WebToApk.workList && window.WebToApk.workCancel)) return;
const requestId = 'signout-' + Date.now();
function onWork(e) {
if (String(e.detail.requestId) !== requestId) return;
window.removeEventListener('appmint:work', onWork);
(e.detail.jobs || []).forEach(function (job) {
WebToApk.workCancel(job.id); // each answers { id, status: 'cancelled' }
});
}
window.addEventListener('appmint:work', onWork);
WebToApk.workList(requestId);
}Observações: responde cancelled mesmo quando nenhuma tarefa tinha esse id. Um salvamento automático que ainda não foi enviado é descartado, então cancele só quando realmente não quiser que ele seja entregue.
workEnqueueOnline ponte#
window.WebToApk.workEnqueueOnline(id: String, url: String, method: String, headersJson: String, payload: String)
Nenhuma permissão necessária; os resultados ecoam como `appmint:work` / window.onAppMintWork.
Descrito pelo seu grupo, Tarefas em segundo plano (WorkManager): salvamento automático durável + sincronização nativa periódica, e não isoladamente.
Exemplo
Entrega uma requisição HTTP ao Android para enviar quando o celular estiver online - mesmo que o usuário feche o app ou reinicie o celular. Use para um salvamento automático confiável.
Retorna: nada diretamente. A resposta chega como o evento appmint:work (e window.onAppMintWork(detail) se você o definir): { id, status: 'enqueued' }, ou { id, status: 'failed', reason } com o motivo invalid_arguments (id vazio ou uma URL que não começa com http) ou enqueue_failed. Requer: nada.
Salvamento automático durável: o mesmo id substitui um salvamento que ainda não foi enviado, então o estado mais recente vence.
function autoSave(state, token) {
if (!(window.WebToApk && window.WebToApk.workEnqueueOnline)) {
showMessage('Offline auto-save works in the installed app only.');
return;
}
WebToApk.workEnqueueOnline(
'autosave', // your job id
'https://api.example.com/save', // http(s) URL
'POST', // POST | PUT | GET ...
JSON.stringify({ Authorization: 'Bearer ' + token }), // headers as a JSON string
JSON.stringify(state) // body as a string ('' for none)
);
}
window.addEventListener('appmint:work', function (e) {
const d = e.detail;
if (d.id !== 'autosave') return;
if (d.status === 'enqueued') showSavedBadge('Will sync when online');
if (d.status === 'failed') showMessage('Could not queue the save: ' + d.reason);
});Enfileire cada envio de formulário como uma tarefa própria (um id único por envio, para o segundo não substituir o primeiro) e espere a resposta do Android:
function queueFeedback(form) {
return new Promise(function (resolve, reject) {
if (!(window.WebToApk && window.WebToApk.workEnqueueOnline)) {
reject(new Error('not_in_app'));
return;
}
const id = 'feedback-' + Date.now();
function onWork(e) {
if (e.detail.id !== id) return; // another job's answer
window.removeEventListener('appmint:work', onWork);
if (e.detail.status === 'enqueued') resolve(id);
else reject(new Error(e.detail.reason)); // invalid_arguments | enqueue_failed
}
window.addEventListener('appmint:work', onWork);
WebToApk.workEnqueueOnline(id, 'https://api.example.com/feedback', 'POST', '{}',
JSON.stringify({ rating: form.rating.value, text: form.text.value }));
});
}Salve uma nota como texto simples com PUT; definir seu próprio Content-Type impede que o padrão JSON seja adicionado:
function saveNote(noteId, text) {
if (!(window.WebToApk && window.WebToApk.workEnqueueOnline)) return;
WebToApk.workEnqueueOnline(
'note-' + noteId, // same note, same id: only the newest text is sent
'https://api.example.com/notes/' + encodeURIComponent(noteId),
'PUT',
JSON.stringify({ 'Content-Type': 'text/plain; charset=utf-8' }),
text
);
}
document.getElementById('note').addEventListener('change', function (e) {
saveNote(e.target.dataset.noteId, e.target.value);
});Observações: enqueued significa que o Android aceitou a tarefa, não que o servidor recebeu; não há evento quando ela é entregue. Regras de entrega: uma resposta 2xx conclui a tarefa; uma resposta 4xx a interrompe (sem nova tentativa); um erro de rede ou 5xx tenta de novo com atrasos crescentes, até 8 vezes. Content-Type: application/json é adicionado, a menos que você defina um. Um GET não envia corpo. O JavaScript da página não roda em segundo plano - só esta requisição nativa.
workList ponte#
window.WebToApk.workList(requestId: String)
Nenhuma permissão necessária; os resultados ecoam como `appmint:work` / window.onAppMintWork.
Descrito pelo seu grupo, Tarefas em segundo plano (WorkManager): salvamento automático durável + sincronização nativa periódica, e não isoladamente.
Exemplo
Lista as tarefas em segundo plano que este app enfileirou ou agendou.
Retorna: nada diretamente. O evento appmint:work (e window.onAppMintWork) responde { requestId, jobs: [{ id, periodic, url, createdAt, pendingDelivery }] }. pendingDelivery é true enquanto uma tarefa única ainda não foi entregue (e sempre para uma tarefa periódica). Requer: nada.
Um pequeno wrapper de Promise que associa a resposta por requestId:
function listJobs() {
return new Promise(function (resolve) {
if (!(window.WebToApk && window.WebToApk.workList)) { resolve([]); return; }
const requestId = 'jobs-' + Date.now();
function onWork(e) {
if (String(e.detail.requestId) !== requestId) return; // not our answer
window.removeEventListener('appmint:work', onWork);
resolve(e.detail.jobs || []);
}
window.addEventListener('appmint:work', onWork);
WebToApk.workList(requestId);
});
}
listJobs().then(function (jobs) {
const unsent = jobs.filter(function (j) { return !j.periodic && j.pendingDelivery; });
document.getElementById('unsent').textContent =
unsent.length ? unsent.length + ' change(s) waiting for network' : 'All changes saved';
});Mostre todas as tarefas em uma tela de configurações, com o momento em que foram enfileiradas:
window.addEventListener('appmint:work', function (e) {
if (e.detail.requestId !== 'settings-jobs') return;
const list = document.getElementById('jobs');
list.innerHTML = '';
(e.detail.jobs || []).forEach(function (job) {
const li = document.createElement('li');
li.textContent = job.id + (job.periodic ? ' (repeats)' : job.pendingDelivery ? ' (waiting)' : '') +
' - since ' + new Date(job.createdAt).toLocaleString();
list.appendChild(li);
});
});
if (window.WebToApk && window.WebToApk.workList) WebToApk.workList('settings-jobs');Quando o app abrir, defina uma chave "Sincronização em segundo plano" conforme a tarefa repetida 'sync' ainda estiver registrada:
window.addEventListener('appmint:work', function (e) {
if (e.detail.requestId !== 'startup') return;
const on = (e.detail.jobs || []).some(function (j) { return j.id === 'sync' && j.periodic; });
document.getElementById('sync-toggle').checked = on;
});
document.addEventListener('DOMContentLoaded', function () {
if (window.WebToApk && window.WebToApk.workList) WebToApk.workList('startup');
});Observações: uma tarefa única sai da lista depois de entregue, rejeitada com um 4xx, ou abandonada após 8 tentativas. Um requestId numérico pode voltar como número, então compare com String(...).
workSchedulePeriodic ponte#
window.WebToApk.workSchedulePeriodic(id: String, url: String, method: String, headersJson: String, payload: String, intervalMinutes: Int)
Nenhuma permissão necessária; os resultados ecoam como `appmint:work` / window.onAppMintWork.
Descrito pelo seu grupo, Tarefas em segundo plano (WorkManager): salvamento automático durável + sincronização nativa periódica, e não isoladamente.
Exemplo
Agenda uma requisição HTTP repetida que o Android envia em segundo plano (quando online), mesmo com o app fechado. Boa para um gatilho de sincronização ou um sinal de vida.
Retorna: nada diretamente. A resposta chega como o evento appmint:work (e window.onAppMintWork(detail)): { id, status: 'scheduled', intervalMinutes }, ou { id, status: 'failed', reason } com o motivo invalid_arguments ou schedule_failed. Requer: nada.
function startBackgroundSync(userId) {
if (!(window.WebToApk && window.WebToApk.workSchedulePeriodic)) {
showMessage('Background sync works in the installed app only.');
return;
}
WebToApk.workSchedulePeriodic(
'sync', // job id (scheduling again updates it)
'https://api.example.com/sync',
'POST',
JSON.stringify({ 'X-User': userId }), // headers as a JSON string
JSON.stringify({ userId: userId }), // the same body is sent every time
30 // minutes; values under 15 become 15
);
}
// Optional page hook instead of addEventListener:
window.onAppMintWork = function (d) {
if (d.id === 'sync' && d.status === 'scheduled') {
console.log('sync every', d.intervalMinutes, 'minutes');
}
if (d.status === 'failed') console.warn('job', d.id, 'failed:', d.reason);
};Um sinal de vida de hora em hora: um GET não envia corpo, então passe uma string vazia, e '{}' quando não precisar de cabeçalhos:
function startHeartbeat(deviceId) {
if (!(window.WebToApk && window.WebToApk.workSchedulePeriodic)) return;
WebToApk.workSchedulePeriodic(
'heartbeat',
'https://api.example.com/ping?device=' + encodeURIComponent(deviceId),
'GET',
'{}',
'',
60
);
}Deixe o usuário escolher a frequência de sincronização e mostre o intervalo que o Android realmente usa (qualquer valor abaixo de 15 volta como 15):
document.getElementById('sync-every').addEventListener('change', function (e) {
if (!(window.WebToApk && window.WebToApk.workSchedulePeriodic)) return;
const minutes = parseInt(e.target.value, 10); // e.g. 5, 30, 120
WebToApk.workSchedulePeriodic('sync', 'https://api.example.com/sync', 'POST', '{}',
JSON.stringify({ reason: 'periodic' }), minutes); // same id: updates the existing job
});
window.addEventListener('appmint:work', function (e) {
const d = e.detail;
if (d.id !== 'sync') return;
if (d.status === 'scheduled') {
document.getElementById('sync-note').textContent = 'Syncing about every ' + d.intervalMinutes + ' minutes';
} else if (d.status === 'failed') {
document.getElementById('sync-note').textContent = 'Could not schedule sync (' + d.reason + ')';
}
});Observações: O Android decide o momento exato; 15 minutos é o menor intervalo, e a economia de bateria pode atrasar execuções. O corpo é fixado quando você agenda; para mudá-lo, agende de novo com o mesmo id. Uma resposta 4xx não cancela uma tarefa periódica; a próxima execução tenta de novo. Pare-a com workCancel('sync').