Créer un APK gratuit

API du pont JavaScript

Tâches en arrière-plan

Un travail qui continue après la fermeture de l'application : un enregistrement automatique durable, une synchronisation périodique.

workCancel pont#

window.WebToApk.workCancel(id: String)

Aucune autorisation nécessaire ; les résultats sont renvoyés sous la forme `appmint:work` / window.onAppMintWork.

Décrit par son groupe, Tâches en arrière-plan (WorkManager) : enregistrement automatique durable + synchronisation native périodique, plutôt que seul.

Exemple

Annule une tâche en arrière-plan (unique ou répétée) par son identifiant et supprime sa requête enregistrée.

Renvoie : rien directement. L'événement appmint:work (et window.onAppMintWork) répond { id, status: 'cancelled' }. Nécessite : rien.

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';
  }
});

Abandonnez un brouillon : annulez son enregistrement automatique qui n'a pas encore été envoyé, puis videz l'éditeur une fois qu'Android a confirmé :

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');
}

À la déconnexion, annulez toutes les tâches de cette application, en utilisant les identifiants que workList indique :

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);
}

Remarques : elle répond cancelled même si aucune tâche n'avait cet identifiant. Un enregistrement automatique qui n'a pas encore été envoyé est abandonné ; n'annulez donc que si vous ne voulez vraiment pas qu'il soit livré.

workEnqueueOnline pont#

window.WebToApk.workEnqueueOnline(id: String, url: String, method: String, headersJson: String, payload: String)

Aucune autorisation nécessaire ; les résultats sont renvoyés sous la forme `appmint:work` / window.onAppMintWork.

Décrit par son groupe, Tâches en arrière-plan (WorkManager) : enregistrement automatique durable + synchronisation native périodique, plutôt que seul.

Exemple

Confie une requête HTTP à Android pour qu'il l'envoie lorsque le téléphone est en ligne - même si l'utilisateur ferme l'application ou redémarre le téléphone. Utilisez-la pour un enregistrement automatique fiable.

Renvoie : rien directement. La réponse arrive sous la forme de l'événement appmint:work (et window.onAppMintWork(detail) si vous le définissez) : { id, status: 'enqueued' }, ou { id, status: 'failed', reason } avec la raison invalid_arguments (identifiant vide ou URL ne commençant pas par http) ou enqueue_failed. Nécessite : rien.

Enregistrement automatique durable : le même identifiant remplace un enregistrement qui n'a pas encore été envoyé, de sorte que l'état le plus récent l'emporte.

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);
});

Mettez chaque envoi de formulaire en file d'attente comme sa propre tâche (un identifiant unique par envoi, pour qu'un second ne remplace pas le premier) et attendez la réponse d'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 }));
  });
}

Enregistrez une note en texte brut avec PUT ; définir votre propre Content-Type empêche l'ajout du type JSON par défaut :

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);
});

Remarques : enqueued signifie qu'Android a accepté la tâche, pas que le serveur l'a reçue ; il n'y a aucun événement lors de la livraison. Règles de livraison : une réponse 2xx termine la tâche ; une réponse 4xx l'arrête (pas de nouvelle tentative) ; une erreur réseau ou 5xx relance avec des délais croissants, jusqu'à 8 tentatives. Content-Type: application/json est ajouté sauf si vous en définissez un. Un GET n'envoie pas de corps. Le JavaScript de la page ne s'exécute pas en arrière-plan - seule cette requête native le fait.

workList pont#

window.WebToApk.workList(requestId: String)

Aucune autorisation nécessaire ; les résultats sont renvoyés sous la forme `appmint:work` / window.onAppMintWork.

Décrit par son groupe, Tâches en arrière-plan (WorkManager) : enregistrement automatique durable + synchronisation native périodique, plutôt que seul.

Exemple

Liste les tâches en arrière-plan que cette application a mises en file d'attente ou planifiées.

Renvoie : rien directement. L'événement appmint:work (et window.onAppMintWork) répond { requestId, jobs: [{ id, periodic, url, createdAt, pendingDelivery }] }. pendingDelivery vaut true tant qu'une tâche unique n'a pas été livrée (et toujours pour une tâche périodique). Nécessite : rien.

Une petite enveloppe Promise qui associe la réponse via 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';
});

Affichez toutes les tâches sur un écran de paramètres, avec l'heure de leur mise en file d'attente :

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');

À l'ouverture de l'application, réglez un interrupteur « Synchronisation en arrière-plan » selon que la tâche répétée 'sync' est toujours enregistrée :

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');
});

Remarques : une tâche unique quitte la liste une fois livrée, rejetée avec une erreur 4xx, ou abandonnée après 8 tentatives. Un requestId numérique peut revenir sous forme de nombre ; comparez donc avec String(...).

workSchedulePeriodic pont#

window.WebToApk.workSchedulePeriodic(id: String, url: String, method: String, headersJson: String, payload: String, intervalMinutes: Int)

Aucune autorisation nécessaire ; les résultats sont renvoyés sous la forme `appmint:work` / window.onAppMintWork.

Décrit par son groupe, Tâches en arrière-plan (WorkManager) : enregistrement automatique durable + synchronisation native périodique, plutôt que seul.

Exemple

Planifie une requête HTTP répétée qu'Android envoie en arrière-plan (lorsqu'il est en ligne), même lorsque l'application est fermée. Pratique pour un déclencheur de synchronisation ou un signal de vie.

Renvoie : rien directement. La réponse arrive sous la forme de l'événement appmint:work (et window.onAppMintWork(detail)) : { id, status: 'scheduled', intervalMinutes }, ou { id, status: 'failed', reason } avec la raison invalid_arguments ou schedule_failed. Nécessite : rien.

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 signal de vie toutes les heures : un GET n'envoie pas de corps, passez donc une chaîne vide, et '{}' lorsque vous n'avez pas besoin d'en-têtes :

function startHeartbeat(deviceId) {
  if (!(window.WebToApk && window.WebToApk.workSchedulePeriodic)) return;
  WebToApk.workSchedulePeriodic(
    'heartbeat',
    'https://api.example.com/ping?device=' + encodeURIComponent(deviceId),
    'GET',
    '{}',
    '',
    60
  );
}

Laissez l'utilisateur choisir la fréquence de synchronisation et affichez l'intervalle qu'Android utilise réellement (toute valeur inférieure à 15 revient comme 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 + ')';
  }
});

Remarques : Android décide du moment exact ; 15 minutes est l'intervalle le plus court, et l'économie de batterie peut retarder les exécutions. Le corps est fixé au moment de la planification ; pour le changer, planifiez à nouveau avec le même identifiant. Une réponse 4xx n'annule pas une tâche périodique ; la prochaine exécution réessaie. Arrêtez-la avec workCancel('sync').

Généré à partir de l'environnement d'exécution de l'application et de ses fichiers d'exemple à chaque compilation de la documentation. Lire en Markdown · Toutes les familles.

Vérifié par rapport au pont publié le 22/10/2026.