0

I have an application with this structure:

- webapp
- - resources
- - - js 
- - - - main.js
- - WEB-INF
- - - views
- - - - index.jsp 

I'm starting to work with progressive webapp, and I just want to make index.jsp work to follow with the other views.

index.jsp

<head>
    <script defer src="resources/js/main.js"></script>
</head>

main.js

navigator.serviceWorker && navigator.serviceWorker.register('resources/js/sw.js').then(function(registration) {
  console.log('Excellent, registered with scope: ', registration.scope);
}).catch(function(error) {
    console.log('Service worker registration failed, error:', error);
    alert(error);
});


sw.js

/** An empty service worker! */
self.addEventListener('fetch', function(event) {
  /** An empty fetch handler! */
});

AppWebConfiguration.java

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
    .addResourceLocations("/resources/");
}


I got the following message from console on Chrome: Excellent, registered with scope: http://localhost:8080/MyProject/resources/js/.
I need the service worker to be created using the root application http://localhost:8080/MyProject, but if I put my sw.js in the root I have not access.

Is there any way to access the sw.js on root or configure to use the root of the application as scope?

I've tried to use navigator.serviceWorker.register('resources/js/sw.js', { scope: './' }) but it didn't work.

BlackBeard
  • 10,246
  • 7
  • 52
  • 62
Robson Farias
  • 151
  • 1
  • 3
  • 14

2 Answers2

1

No, it's not possible to use a wider scope than where the SW.js is located. In other words: you can use the scope option to limit the SW, but you cannot have it extend the SW's scope upwards the directory structure.

In order to have "/" as your scope, you have to serve the SW.js from "/SW.js".

However, you could add a special header to your html that gives the SW this wider scope access permisson. Read more about it here.

pate
  • 4,937
  • 1
  • 19
  • 25
1

I solved my problem mapping the service-worker to the root of the application, as suggested, using the ResourceHandlers of the Spring.

AppWebConfiguration.java

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**")
        .addResourceLocations("/resources/");
    registry.addResourceHandler("/**")
        .addResourceLocations("/resources/js/sw.js");
}

With the following, I can access the sw.js at the root of the application with the following script:

main.js

navigator.serviceWorker && navigator.serviceWorker.register('./sw.js').then(function(registration) {
  console.log('Excellent, registered with scope: ', registration.scope);
}).catch(function(error) {
    console.log('Service worker registration failed, error:', error);
    alert(error);
});
Robson Farias
  • 151
  • 1
  • 3
  • 14