Prise en main
Copiez un prompt de configuration incluant les étapes d'installation et le guide markdown complet pour ce plugin.
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-webview-crash`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/docs/plugins/webview-crash/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
Installer
Section intitulée « Installation »Vous pouvez utiliser notre configuration assistée par IA pour installer le plugin. Ajoutez les skills Capgo à votre outil d'IA avec la commande suivante :
bunx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-pluginsUtilisez ensuite le prompt suivant :
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-webview-crash` plugin in my project.Si vous préférez une installation manuelle, installez le plugin en exécutant les commandes suivantes et suivez les instructions spécifiques à chaque plateforme ci-dessous :
bun add @capgo/capacitor-webview-crashbunx cap syncImporter
Section intitulée « Import »import { WebViewCrash } from '@capgo/capacitor-webview-crash';Démarrage rapide
Section intitulée « Démarrage rapide »import { WebViewCrash } from '@capgo/capacitor-webview-crash';
const result = await WebViewCrash.getPendingCrashInfo();console.log(result);Exemple : clearPendingCrashInfo
Section intitulée « Exemple : clearPendingCrashInfo »import { WebViewCrash } from '@capgo/capacitor-webview-crash';
await WebViewCrash.clearPendingCrashInfo();Exemple : simulateCrashRecovery
Section intitulée « Exemple : simulateCrashRecovery »import { WebViewCrash } from '@capgo/capacitor-webview-crash';
const result = await WebViewCrash.simulateCrashRecovery();console.log(result);Erreurs courantes
Section intitulée « Erreurs courantes »- Écouteurs: supprimez les handles lors du démontage des écrans.
- Sync native : exécuter
bunx cap syncaprès les mises à jour du plugin. - Source de vérité : fiez-vous
src/definitions.tsau repo GitHub.
Flux de récupération recommandé
Section intitulée « Flux de récupération recommandé »Attachez des listeners le plus tôt possible lors du démarrage de votre application pour que le runtime récupéré puisse réagir avant que les utilisateurs ne continuent leur navigation :
import { WebViewCrash } from '@capgo/capacitor-webview-crash';
await WebViewCrash.addListener('webViewRestoredAfterCrash', async (info) => { console.log('Recovered after a WebView crash', info);
// Rehydrate critical state, reopen the correct screen, or prompt the user to retry. await WebViewCrash.clearPendingCrashInfo();});
await WebViewCrash.addListener('webViewRestoredAfterRestart', async (info) => { console.log('Recovered after a native WebView restart', info); await WebViewCrash.clearPendingCrashInfo();});
const pending = await WebViewCrash.getPendingCrashInfo();// Note: the listener callback may have already cleared the pending marker.if (pending.value) { console.log('Pending crash or restart marker', pending.value);}Redémarrage natif automatique
Section intitulée « Redémarrage natif automatique »Configurez les options de redémarrage dans capacitor.config.ts pour que la décision reste dans le code natif, même si le runtime JavaScript a crashé ou n'est pas encore chargé :
import type { CapacitorConfig } from '@capacitor/cli';import type { WebViewCrashPluginConfig } from '@capgo/capacitor-webview-crash';
const webViewCrash: WebViewCrashPluginConfig = { // Enabled by default. Keep this on for long-running apps. restartOnCrash: true,
// Use a 5-field cron schedule in the device local timezone. // Do not combine restartCron with an active restartIntervalMs. restartCron: '0 3 * * *',
// Optional delay before restarting after a crash. restartAfterCrashDelayMs: 0,};
const config: CapacitorConfig = { plugins: { WebViewCrash: webViewCrash, },};
export default config;Utiliser restartIntervalMs pour les applications toujours actives où les utilisateurs peuvent laisser la même WebView ouverte pendant des jours : écrans de kiosque, dashboards de salle de contrôle, scanners d'entrepôt, terminaux de point de vente, tablettes de flotte et affichage dynamique. Utilisez restartCron pour les redémarrages à heure fixe comme 0 3 * * * pour un redémarrage quotidien à 03:00 dans le fuseau horaire local de l'appareil. Les redémarrages programmés écrivent un marqueur en attente avec reason: 'periodicRestart', puis Android recrée l'activité hôte et iOS reconstruit la vue du bridge Capacitor afin qu'un nouveau WKWebView soit créé à partir du code natif.
Choisissez un intervalle ou un planning cron que votre produit peut tolérer. restartCron supporte *, listes, plages et étapes. Ne configurez pas les deux programmes en même temps : l'initialisation native génère une erreur de configuration fatale lorsque restartCron est défini et restartIntervalMs est supérieur à 0. Un redémarrage crée un nouveau runtime JavaScript ; pensez donc à persister les événements en file d'attente, l'état des formulaires non enregistrés et l'état de navigation actuel avant d'utiliser des plannings agressifs.
Redémarrage natif manuel
Section intitulée « Redémarrage natif manuel »Appelez restartWebView() lorsque le runtime JavaScript actuel décide de remplacer proactivement la WebView native, par exemple après un workflow gourmand en mémoire ou avant de lancer une session longue sans surveillance :
await WebViewCrash.restartWebView();La méthode écrit un marqueur en attente avec reason: 'manualRestart', résout l'appel actuel, puis demande au code natif de créer une nouvelle WebView. Android recrée l'activité hôte. iOS reconstruit la vue de pont Capacitor afin qu'une nouvelle WKWebView soit créée au lieu de recharger la page actuelle.
Aperçu de API
Section intitulée « Aperçu de API »getPendingCrashInfo
Section intitulée « getPendingCrashInfo »Renvoie le crash natif stocké ou le marqueur de redémarrage, ou null lorsque rien n'est en attente.
const pending = await WebViewCrash.getPendingCrashInfo();if (pending.value) { console.log(pending.value.platform, pending.value.reason);}clearPendingCrashInfo
Section intitulée « clearPendingCrashInfo »Efface le marqueur stocké une fois que votre gestion de récupération est terminée.
await WebViewCrash.clearPendingCrashInfo();simulateCrashRecovery
Section intitulée « simulateCrashRecovery »Crée un faux marqueur de crash pour que la QA et le débogage local puissent tester le chemin de récupération sans faire planter une véritable WebView.
const simulated = await WebViewCrash.simulateCrashRecovery();console.log(simulated.value);restartWebView
Section intitulée « restartWebView »Stocke un marqueur de redémarrage manuel et demande au code natif de créer une nouvelle WebView.
await WebViewCrash.restartWebView();Notes sur les plateformes
Section intitulée « Notes sur les plateformes »- Android stocke les métadonnées de crash de
onRenderProcessGone, y comprisdidCrashetrendererPriorityAtExitlorsque la plateforme les fournit. - iOS stocke les métadonnées de crash de
webViewWebContentProcessDidTerminateet ajoute l'état actuel de l'application si disponible. - Les redémarrages manuels et programmés créent une nouvelle WebView. Android recrée l'activité hôte ; iOS reconstruit la vue du bridge Capacitor.
- Les redémarrages programmés utilisent
reason: 'periodicRestart'; les redémarrages manuels utilisentreason: 'manualRestart'. - Le Web ne détecte pas les crashs réels du renderer. L'implémentation web simule uniquement le comportement via le local storage.
Référence de type
Section intitulée « Référence de type »PendingCrashInfoResult
Section intitulée « PendingCrashInfoResult »export interface PendingCrashInfoResult { /** * Stored crash or restart metadata, or `null` when no marker is pending. */ value: WebViewCrashInfo | null;}WebViewCrashPluginConfig
Section intitulée « WebViewCrashPluginConfig »export interface WebViewCrashPluginConfig { /** * Restart the WebView from native code when the renderer process dies. * * @default true */ restartOnCrash?: boolean;
/** * Fixed native interval, in milliseconds, for proactively replacing long-running WebViews. * * Set to `0` to disable interval restarts. Do not combine an active interval * with `restartCron`; native initialization fails fast when both schedules are configured. * * @default 0 */ restartIntervalMs?: number;
/** * Cron schedule for proactively replacing long-running WebViews. * * Uses standard 5-field cron syntax in the device local timezone: * `minute hour day-of-month month day-of-week`. * * Examples: * - `0 3 * * *` restarts every day at 03:00. * - `0,30 * * * *` restarts every 30 minutes. * * Do not combine this with an active `restartIntervalMs`; native initialization * fails fast when both schedules are configured. */ restartCron?: string;
/** * Delay, in milliseconds, before restarting after a crash. * * @default 0 */ restartAfterCrashDelayMs?: number;}WebViewCrashInfo
Section intitulée « WebViewCrashInfo »export interface WebViewCrashInfo { /** * Platform that detected and stored the marker. */ platform: WebViewCrashPlatform;
/** * Unix timestamp in milliseconds for when the marker was written. */ timestamp: number;
/** * ISO-8601 version of `timestamp`. */ timestampISO: string;
/** * Platform-specific reason for the crash or restart marker. */ reason: WebViewCrashReason;
/** * Last known WebView URL when the marker was written. */ url?: string;
/** * Android-only hint from `RenderProcessGoneDetail.didCrash()`. */ didCrash?: boolean;
/** * Android-only renderer priority reported at exit. */ rendererPriorityAtExit?: number;
/** * iOS-only application state captured when the WebView process died. */ appState?: WebViewCrashAppState;}WebViewCrashPlatform
Section intitulée « WebViewCrashPlatform »export type WebViewCrashPlatform = 'android' | 'ios' | 'web';WebViewCrashReason
Section intitulée « WebViewCrashReason »export type WebViewCrashReason = | 'renderProcessGone' | 'webContentProcessDidTerminate' | 'periodicRestart' | 'manualRestart' | 'simulated';WebViewCrashAppState
Section intitulée « WebViewCrashAppState »export type WebViewCrashAppState = 'active' | 'inactive' | 'background' | 'unknown';Source de vérité
Section intitulée « Source de vérité »Cette page est générée à partir de src/definitions.ts. Relancez la synchronisation lorsque l’API public change en amont.
Continuer depuis Getting Started
Section intitulée « Continuer après Prise en main »Si vous utilisez Prise en main pour planifier le comportement des médias et de l'interface natifs, connectez-l’à Utiliser @capgo/capacitor-webview-crash pour la fonctionnalité native dans Utiliser @capgo/capacitor-webview-crash, Utiliser @capgo/capacitor-live-activities pour la capacité native dans Utiliser @capgo/capacitor-live-activities @capgo/capacitor-live-activities pour le détail d'implémentation dans @capgo/capacitor-live-activities Utiliser @capgo/capacitor-video-player pour la capacité native dans Utiliser @capgo/capacitor-video-player, et @capgo/capacitor-video-player pour le détail d'implémentation dans @capgo/capacitor-video-player.