Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Network plugin doesn't work on PWA app Ionic 4

I use network plugin and it is working fine on the device on native/Cordova. But it is not working on the PWA app (i.e. when there is no wifi). Any reason for that? According to the above doc, it should work on the browser too.

Note: I have followed this doc to create a PWA app.

network-state.ts

import { Injectable } from '@angular/core';
import { Subscription } from 'rxjs';
import { Network } from '@ionic-native/network/ngx';
import { ShowToastService } from './show-toast.service';

@Injectable({
  providedIn: 'root'
})
export class NetworkStateService {

  private connectSubscription$: Subscription = null;

  constructor(private network: Network,
    private showToastService: ShowToastService) { }

  WatchConnection() {
    if (this.connectSubscription$) { this.connectSubscription$.unsubscribe(); }
    this.connectSubscription$ = this.network.onDisconnect().subscribe(() => {
      this.showToastService.showNetworkStateErrorToast('Your internet seems to be down! Please check your network settings!');
      if (this.connectSubscription$) { this.connectSubscription$.unsubscribe(); }
      this.connectSubscription$ = this.network.onConnect().subscribe(() => {
        setTimeout(() => {
          this.showToastService.toast.dismiss();
          if (this.network.type === 'wifi' || this.network.type === '4g' || this.network.type === '3g' || this.network.type === '2g' || this.network.type === 'cellular' || this.network.type === 'none') {
            this.showToastService.showNetworkStateSuccessToast('Internet connection available!');
            this.WatchConnection();
          }
        }, 3000);
      });
    });
  }

}

app.component.ts

 async initializeApp() {
    await this.platform.ready();
    this.statusBar.styleDefault();
    this.splashScreen.hide();

    this.networkStateService.WatchConnection();// here

  }
like image 694
Sampath Avatar asked Aug 31 '25 10:08

Sampath


1 Answers

Ionic Native it self only calls plugins when there is cordova available. In the code here, we check to see if cordova is on window and if not, we log a warning.

In the guide you're following, you're just publishing as a PWA using the standard angular browser build, which will not include cordova, nor should it. Since there is no cordova being included in the build, ionic-native is behaving as expected.

An alternative option here is to use capacitor, which has a network plugin and works better with existing deployment tools (angular, pwa)

Here's a link to a getting started guide and a reference guide

like image 169
mhartington Avatar answered Sep 03 '25 00:09

mhartington