API del bridge JavaScript
Processi in background
Lavoro che continua anche dopo la chiusura dell'app: un salvataggio automatico durevole, una sincronizzazione periodica.
workCancel bridge#
window.WebToApk.workCancel(id: String)
Non serve alcuna autorizzazione; i risultati tornano come `appmint:work` / window.onAppMintWork.
Descritta insieme al suo gruppo, Processi in background (WorkManager): salvataggio automatico durevole + sincronizzazione nativa periodica, e non da sola.
Esempio
Annulla un processo in background (singolo o ripetuto) tramite il suo id ed elimina la richiesta salvata.
Restituisce: niente direttamente. L'evento appmint:work (e window.onAppMintWork) risponde { id, status: 'cancelled' }. Richiede: niente.
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';
}
});Scarta una bozza: annulla il suo salvataggio automatico non ancora inviato, poi svuota l'editor quando Android conferma:
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');
}Alla disconnessione, annulla ogni processo di questa app, usando gli id riportati da workList:
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);
}Note: risponde cancelled anche quando nessun processo aveva quell'id. Un salvataggio automatico non ancora inviato viene scartato, quindi annulla solo quando non vuoi davvero che venga consegnato.
workEnqueueOnline bridge#
window.WebToApk.workEnqueueOnline(id: String, url: String, method: String, headersJson: String, payload: String)
Non serve alcuna autorizzazione; i risultati tornano come `appmint:work` / window.onAppMintWork.
Descritta insieme al suo gruppo, Processi in background (WorkManager): salvataggio automatico durevole + sincronizzazione nativa periodica, e non da sola.
Esempio
Affida ad Android una richiesta HTTP da inviare quando il telefono è online - anche se l'utente chiude l'app o riavvia il telefono. Usala per un salvataggio automatico affidabile.
Restituisce: niente direttamente. La risposta arriva come evento appmint:work (e window.onAppMintWork(detail) se lo definisci): { id, status: 'enqueued' }, oppure { id, status: 'failed', reason } con motivo invalid_arguments (id vuoto o URL che non inizia con http) o enqueue_failed. Richiede: niente.
Salvataggio automatico durevole: lo stesso id sostituisce un salvataggio non ancora inviato, così vince lo stato più recente.
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);
});Metti in coda ogni invio di modulo come processo a sé (un id univoco per invio, così un secondo non sostituisce il primo) e attendi la risposta di 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 }));
});
}Salva una nota come testo semplice con PUT; impostando il tuo Content-Type si evita che venga aggiunto quello JSON predefinito:
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);
});Note: enqueued significa che Android ha accettato il processo, non che il server l'abbia ricevuto; non c'è alcun evento quando viene consegnato. Regole di consegna: una risposta 2xx completa il processo; una risposta 4xx lo ferma (nessun nuovo tentativo); un errore di rete o un 5xx riprova con ritardi crescenti, fino a 8 tentativi. Content-Type: application/json viene aggiunto a meno che tu non ne imposti uno. Un GET non invia corpo. Il JavaScript della pagina non viene eseguito in background - solo questa richiesta nativa.
workList bridge#
window.WebToApk.workList(requestId: String)
Non serve alcuna autorizzazione; i risultati tornano come `appmint:work` / window.onAppMintWork.
Descritta insieme al suo gruppo, Processi in background (WorkManager): salvataggio automatico durevole + sincronizzazione nativa periodica, e non da sola.
Esempio
Elenca i processi in background che questa app ha messo in coda o pianificato.
Restituisce: niente direttamente. L'evento appmint:work (e window.onAppMintWork) risponde { requestId, jobs: [{ id, periodic, url, createdAt, pendingDelivery }] }. pendingDelivery è true finché un processo singolo non è stato ancora consegnato (e sempre per un processo periodico). Richiede: niente.
Un piccolo wrapper Promise che abbina la risposta tramite 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';
});Mostra ogni processo in una schermata delle impostazioni, con l'ora in cui è stato messo in coda:
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');All'apertura dell'app, imposta un interruttore «Sincronizzazione in background» in base al fatto che il processo ripetuto 'sync' sia ancora registrato:
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');
});Note: un processo singolo esce dall'elenco una volta consegnato, rifiutato con un 4xx, o abbandonato dopo 8 tentativi. Un requestId numerico può tornare come numero, quindi confronta con String(...).
workSchedulePeriodic bridge#
window.WebToApk.workSchedulePeriodic(id: String, url: String, method: String, headersJson: String, payload: String, intervalMinutes: Int)
Non serve alcuna autorizzazione; i risultati tornano come `appmint:work` / window.onAppMintWork.
Descritta insieme al suo gruppo, Processi in background (WorkManager): salvataggio automatico durevole + sincronizzazione nativa periodica, e non da sola.
Esempio
Pianifica una richiesta HTTP ripetuta che Android invia in background (quando è online), anche con l'app chiusa. Utile per attivare una sincronizzazione o per un heartbeat.
Restituisce: niente direttamente. La risposta arriva come evento appmint:work (e window.onAppMintWork(detail)): { id, status: 'scheduled', intervalMinutes }, oppure { id, status: 'failed', reason } con motivo invalid_arguments o schedule_failed. Richiede: niente.
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);
};Un battito ogni ora: un GET non invia corpo, quindi passa una stringa vuota, e '{}' quando non servono intestazioni:
function startHeartbeat(deviceId) {
if (!(window.WebToApk && window.WebToApk.workSchedulePeriodic)) return;
WebToApk.workSchedulePeriodic(
'heartbeat',
'https://api.example.com/ping?device=' + encodeURIComponent(deviceId),
'GET',
'{}',
'',
60
);
}Lascia che l'utente scelga ogni quanto sincronizzare e mostra l'intervallo che Android usa davvero (qualsiasi valore inferiore a 15 torna come 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 + ')';
}
});Note: Android decide il momento esatto; 15 minuti è l'intervallo più breve e il risparmio energetico può ritardare le esecuzioni. Il corpo viene fissato quando pianifichi; per cambiarlo, pianifica di nuovo con lo stesso id. Una risposta 4xx non annulla un processo periodico; la prossima esecuzione riprova. Fermalo con workCancel('sync').