question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

bug: service worker server.url not injecting capacitor

See original GitHub issue

Bug Report

Capacitor Version

Latest Dependencies:

  @capacitor/cli: 3.3.2
  @capacitor/core: 3.3.2
  @capacitor/android: 3.3.2
  @capacitor/ios: 3.3.2

Installed Dependencies:

  @capacitor/ios: not installed
  @capacitor/cli: 3.3.2
  @capacitor/android: 3.3.2
  @capacitor/core: 3.3.2

Platform(s)

Current Behavior

Calling any native plugins when an app is served from an Angular service worker causes the plugins to fail. Using server.url to load the site on Android. image

Platform ready does not help for this.

Expected Behavior

Capacitor needs to be injected when a site is served through a service worker.

Code Reproduction

app.module.ts

export function init_app(appLoadService: AppLoadService) {
  return () => appLoadService.initApp();
}

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: environment.production,
      // Register the ServiceWorker as soon as the app is stable
      // or after 30 seconds (whichever comes first).
      registrationStrategy: 'registerWhenStable:30000',
    }),
  ],
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    {
      provide: APP_INITIALIZER,
      useFactory: init_app,
      deps: [AppLoadService],
      multi: true,
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

app-load-service.ts

@Injectable({
  providedIn: 'root',
})
export class AppLoadService {
  constructor(
    private device: DeviceInfo,
    private platform: Platform
  ) {}

  async initApp(): Promise<any> {
    await this.platform.ready();

    SplashScreen.hide(); // breaks
  }
}

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:6
  • Comments:40

github_iconTop GitHub Comments

3reactions
leo-buneevcommented, Nov 14, 2022

Full working workaround with latest Capacitor and latest Android - compiled from ideas of @yoyo930021

public class MainActivity extends BridgeActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    if(Build.VERSION.SDK_INT >= 24 ){
      ServiceWorkerController swController = ServiceWorkerController.getInstance();

      swController.setServiceWorkerClient(new ServiceWorkerClient() {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) {
          if(request.getUrl().toString().contains("index.html")) {
            // Hack to help capacitor's "shouldInterceptRequest"
            request.getRequestHeaders().put("Accept", "text/html");
          }
          var result =  bridge.getLocalServer().shouldInterceptRequest(request);
          return result;
        }
      });
    }
  }
}

Note that depending on your SW setup root file may not be called “index.html”. In that case feel free to adjust if(request.getUrl().toString().contains("index.html")) condition above according to your app’s setup

3reactions
yoyo930021commented, May 6, 2022

I using this answer and work for me on android with capacitor 2. https://stackoverflow.com/questions/55894716/how-to-package-a-hosted-web-app-with-ionic-capacitor/55916297#55916297

but I replace ServiceWorkerController to ServiceWorkerControllerCompat for my case.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Plugins not working through service worker - Capacitor
Hi friends. I am wondering if anyone has any input or can work with me to try and get this issue resolved: bug:...
Read more >
Troubleshooting Android Issues | Capacitor Documentation
If still getting the "Plugin not implemented" error, make sure you are not using service workers, that prevents Capacitor's and Plugins code from...
Read more >
Service Worker Registration Failed - Stack Overflow
SW registration failed with error SecurityError: Failed to register a ServiceWorker: The URL protocol of the current origin ('null') is not ...
Read more >
Getting started with service workers - Angular
Adding a service worker to your projectlink. To set up the Angular service worker in your project, use the CLI command ng add...
Read more >
Firebase JavaScript SDK Release Notes - Google
Updated the SDK to recognize Capacitor apps by detecting the capacitor: protocol. ... Fixed a bug where @firebase/app-check-types was not included as a ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found