How to register a service worker in Ruby on Rails?

I am trying to register a service worker in Ruby On Rails to implement GCM push notifications. But nothing happens. Please see my code below:

if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/assets/service-worker.js') .then(initialiseState); } else { window.Demo.debug.log('Service workers aren\'t supported in this browser.'); 

This part is working fine. But, when I call navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) , nothing happens.

I was looking for a search engine and they helped me very little.

Can someone help me?

+6
source share
2 answers

The employer of the service script, service-worker.js in your case, needs to serve either the URL path of the same directory, or the page with its registration, or subpath.

You use the path /assets/service-worker.js , so if the registration page is not submitted with /assets/ , it will stop working. If you put .catch(function(error) { console.warn(error); }) at the end of your register() (which Promise returns, you will see an error message.

The easiest way to do this is to make sure that service-worker.js served from the same directory as the web page, and then calls register('service-worker.js') , which uses the relative path to the same directory.

+2
source

Check out the serviceworker-rails gem.

As Jeff mentioned, the way that a service worker should be "in sight". This pearl allows the proxy server to serve requests in the root directory (or any other path) to the resource in the Rails pipeline.

For example, if your serviceworker script access point is in app/assets/javascripts/nested/directory/serviceworker.js in a Rails project, you can configure the application to render the script with /serviceworker.js with a simple configuration setting:

 # config/application.rb config.serviceworker.routes.draw do match "/serviceworker.js" => "nested/directory/serviceworker.js" end 
+2
source

All Articles