How to Use Ionic Native Plugins in the Browser (Step-by-Step Guide)

This post explains how to use Ionic native plugins in a browser environment by mocking and overriding classes.

May 30, 2017 · 2 min read · 251 Words · -Views -Comments · Programming
Mobile Development 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

Official doc

Using native plugins in the browser

Ionic Native has 130+ mobile SDK plugins, making it possible to build powerful Ionic apps.

Historically, testing these native plugins in the browser was difficult. Developers had to test on physical devices or emulators, which is slow.

Ionic Native 3.0 allows developers to mock these plugins in the browser by overriding classes. You can provide test data or access native APIs like HealthKit.

This means many Ionic apps can be fully built in the browser without deploying to a device or simulator. A huge speed boost.

Mocking plugins

To use Ionic native plugins in the browser, extend the plugin class and override some methods.

Let’s mock the Camera plugin to return an image.

First import Camera in the root module.

import { Camera } from '@ionic-native/camera';

Then create a class that extends Camera and mocks an implementation.

providers: [
  { provide: Camera, useClass: CameraMock }
]

Below is a full example:

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

import { Camera } from '@ionic-native/camera';

class CameraMock extends Camera {
  getPicture(options) {
    return new Promise((resolve, reject) => {
      resolve("BASE_64_ENCODED_DATA_GOES_HERE");
    })
  }
}

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    { provide: Camera, useClass: CameraMock }
  ]
})
export class AppModule {}
Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover