4

i've been create new project PWA. when i develop not using node js for (socket.io running) just running in offline like i expected and needed.

but when integration with nodejs server. when go online the app running well not get any problem. but when i change to offline mode my service work not run but show offline browser.

this my code node js server:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var cors = require('cors');

app.use(cors());
app.use(express.static(__dirname + '/'));

app.use(function(req, res, next){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});


io.on('connection', function(socket) {
  console.log('new connection');

  socket.on('afterBid', function(data) {
    io.emit('bcCurrentBid', {
      current_bidding: data.auction_current_bidding,
      user_id_dominated: data.user_id_dominated
    });
  });

});

server.listen(9991, function() {
  console.log('server up and running at 2205 port');
});

and this is my service register in index js

if ('serviceWorker' in navigator && 'PushManager' in window) {
  console.log('Service Worker and Push is supported');

   window.addEventListener('load', function() {
   navigator.serviceWorker
             .register('./service-worker.js')
             .then(function() { console.log('Service Worker Registered'); });
   });
 }

and this is my service-worker.js file:

var cacheName = 'Auction-v2';
var filesToCache = [
  'index.html',
  'server.js',
  '/',
  './app/app.js',
  './app/listAuctionController.js',
  './app/auctionDetailController.js',
  './app/service/auctionDataService.js',
  './media/frontend/images/auction_logo_white.png',
  // './media/frontend/',
  // './media/catalog/',
  // './view/',
  './lib/css/materialize.min.css',
  './lib/css/owl.carousel.min.css',
  './lib/css/jquery.countdown.css',
  './lib/css/owl.theme.default.min.css',
  './lib/css/materialize-icon.css',
  './lib/js/jquery.min.js',
  './lib/js/jquery.lazyLoad.js',
  './lib/js/jquery.maskMoney.js',
  './lib/js/jquery.countdown.min.js',
  './lib/js/materialize.min.js',
  './lib/js/owl.carousel.min.js',
  './lib/js/angular/angular.min.js',
  './lib/js/angular/angular-route.min.js',
  './lib/js/angular/angular-sanitize.min.js',
  './lib/js/angular/angular-locale_id-id.js',
  './lib/js/angular/angular-animate.min.js',
];

var dataCacheName = 'Auction-Data-v1';

// SW Install
self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    })
  );
});




self.addEventListener('fetch', function(e) {
  // console.log('[Service Worker] Fetch', e.request.url);
  var dataUrl = '/backendFrame/public/api/v1/';
  var dataUrl2 = '/view/';
  if (e.request.url.indexOf(dataUrl) > -1 || e.request.url.indexOf(dataUrl2)) {
    /*
     * When the request URL contains dataUrl, the app is asking for fresh
     * weather data. In this case, the service worker always goes to the
     * network and then caches the response. This is called the "Cache then
     * network" strategy:
     * https://jakearchibald.com/2014/offline-cookbook/#cache-then-network
     */
    e.respondWith(
      caches.open(dataCacheName).then(function(cache) {
        return fetch(e.request).then(function(response){
          // console.log('url to cache =' + e.request.url);
          cache.put(e.request.url, response.clone());
          return response;
        });
      })
    );
  } else {
    /*
     * The app is asking for app shell files. In this scenario the app uses the
     * "Cache, falling back to the network" offline strategy:
     * https://jakearchibald.com/2014/offline-cookbook/#cache-falling-back-to-network
     */
    e.respondWith(
      caches.match(e.request).then(function(response) {
        return response || fetch(e.request);
      })
    );
  }
});

// SW Activate
self.addEventListener('activate', function(e) {
  console.log('[ServiceWorker] Activate');
  e.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (key !== cacheName  && key !== dataCacheName) {
          console.log('[ServiceWorker] Removing old cache', key);
          return caches.delete(key);
        }
      }));
    })
  );
  return self.clients.claim();
});

thanks maybe someone can give me solution

  • Without seeing the contents of your `service-worker.js`, it's hard to give much feedback. One general piece of advice is that service workers can't intercept WebSocket API requests/responses, i.e. it won't be able to handle your socket.io traffic. – Jeff Posnick Mar 29 '17 at 19:16
  • @JeffPosnick but can service worker and nodejs server run toghether?.. i just need run my node js server and when offline mode service worker be able to show app from the cache – Medianto Jaelani Mar 30 '17 at 02:18

2 Answers2

2

I posted a similar question here and got an answer : Service Worker not working in Offline mode with node js server

To make it short, keep in mind the service worker's scope is its own directory and folders below... and it cannot access your lib or app directories...

In more detail, this means that if your content starts at https://example.com/, your service worker must live at https://example.com/service-worker.js. It won't function right if you put it as https://example.com/js/service-worker.js.

Ed.
  • 1,992
  • 1
  • 13
  • 30
B. B.
  • 131
  • 1
  • 8
1

The service worker is just a javascript file served from your webserver. It doesn't matter if it's node.js or not.

Have you checked the 'application' tab in the chrome debugging tools to see if the service worker is loaded? If it is, please share the code of your 'service-worker.js' file. You can also add a 'catch' part when registering the service worker. That may show you what is going on if the service worker can't be loaded.

window.addEventListener('load', function() {
  navigator.serviceWorker
    .register('./service-worker.js')
    .then(function() { console.log('Service Worker Registered'); })
    
    .catch(function (err) {
            console.log('ServiceWorker registration failed: ', err);
    });
    
});
Sorskoot
  • 10,190
  • 6
  • 55
  • 98
  • i was edit my question and add my service-worker.js file the problem that i get is.. when i run without nodejs my apps can running in offline mode with service worker @Sorskoot – Medianto Jaelani Mar 31 '17 at 06:36