Chapter 10 of 12 ~14 min read

App Lifecycle & Events

Side-by-side Cordova vs Capacitor — practical migration with working code.


App State Events

Cordova
document.addEventListener('deviceready', () => {
  console.log('App ready');
});

document.addEventListener('pause', () => {
  // App went to background
  saveState();
});

document.addEventListener('resume', () => {
  // App came to foreground
  refreshData();
});

document.addEventListener('backbutton', () => {
  // Android back button
  history.back();
}, false);

document.addEventListener('resign', () => {
  // iOS: about to lose focus
});
document.addEventListener('active', () => {
  // iOS: regained focus
});
Capacitor
import { App, AppState, URLOpenListenerEvent }
  from '@capacitor/app';

// App state changes
App.addListener('appStateChange',
  (state: AppState) => {
    if (!state.isActive) {
      // Went to background
      saveState();
    } else {
      // Came to foreground
      refreshData();
    }
  }
);

// Back button (Android)
App.addListener('backButton',
  ({ canGoBack }) => {
    if (canGoBack) {
      window.history.back();
    } else {
      App.exitApp();
    }
  }
);

// Deep links
App.addListener('appUrlOpen',
  (event: URLOpenListenerEvent) => {
    const slug = event.url.split('.com').pop();
    if (slug) router.navigate([slug]);
  }
);

Status Bar & Safe Areas

Cordova
StatusBar.styleDefault();
StatusBar.backgroundColorByHexString('#3880FF');
StatusBar.overlaysWebView(false);

// In config.xml:
// <preference name="StatusBarOverlaysWebView"
//             value="false" />
Capacitor
import { StatusBar, Style } from '@capacitor/status-bar';

await StatusBar.setStyle({ style: Style.Dark });
await StatusBar.setBackgroundColor({ color: '#3880FF' });
await StatusBar.show();
await StatusBar.hide();

// In capacitor.config.ts:
// plugins: {
//   StatusBar: { style: 'dark', overlaysWebView: false }
// }