Use Capacitor plugins on the web with PWA Elements

Jorge Vergara pointing at a target showing an arrow in the bullseye

Some Capacitor plugins, such as Camera, have web platform support, which lets Capacitor use a web implementation so that your code works as-is on Android, iOS, and the Web.

To enable this, the Ionic team created a package called pwa-elements, to install it, let’s open our terminal, in the root of our application and type:

npm install @ionic/pwa-elements

And then go into the src/main.ts file and define the custom elements:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

// Here you import it
import { defineCustomElements } from '@ionic/pwa-elements/loader';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch(err => console.log(err));

// Call the element loader after the platform has been bootstrapped
defineCustomElements(window);

And that is it. Now you can use the plugin both in native and the web.

To know if a plugin has web support, you can go into the plugins page and see the section called PWA notes. As shown in the banner image at the top of this page.