Not seeing changes made to static files when using service worker - reactjs

I have registered a service worker for a reactjs app.
I am using the cache api with it. When I make changes to my service worker script the activate event is called and I am able to update the the service worker
The challenge is with making changes to the source files. I am unable to see these changes even after updating the service worker, the only time I see changes is when I manually register a new service worker all together.
this is a snippet of the activate event listener
self.addEventListener('activate', event => {
const expectedCacheNames = Object.values(CURRENT_CACHES);
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if(!expectedCacheNames.includes(cacheName)) {
console.log('Deleting out of date cache: ', cacheName);
return caches.delete(cacheName);
}
})
)
})
)
});
Is this problem specific to react?
code structured as follows
/src
/components
index.js //this is where I register service worker after calling ReactDOM
/public
sw.js
//other assests ...

Related

When attempting to stub a request in Cypress IO (JS) against a React app using fetch, the requests still call through to the server

I'm using Cypress to create some specs against my React app. My react app uses fetch to fetch data from an external api (isomorphic-fetch)
The fetch requests in my app are like so
import fetch from 'fetch'
...
fetch('http://www.external-server.com/ideas.json')
.then((response) => {
if (response.status >= 400) {
}
return response.json().then((result) => {
this._data = result
this._data((ele) => ele.key = ele.id)
});
})
In my Cypress specs, I want my regular specs to hit my lcoahost:3000 to get the initial page (which houses my React app). My react app in turn would normally make an external request (http://www.external-server.com/ideas.json) but in my specs I want to stub out that request and have that endpoint return fake data in my specs only.
The Cypress docs for cy.route() here, describe that I should be able to do something like
cy.server()
cy.route('http://www.external-server.com/ideas.json', [
{
id: 1,
name: 'john'
}
])
I attempted to put this into a beforeEach that runs in the context of my spec (thus running before every spec).
You will note that when I run the specs in the Cypress test running, it appears in the console output that the endpoint SHOULD be stubbed.
However, by examination, I can see that my app is in fact making the request to the real server, and calling the real endpoint (not stubbing it).
I tested several times and I am certain this is the behavior.
I found a solution online I will post below to answer my question
the solution is add to cypress/support/commands.js
this small hack will turn the window fetch into a no-op (disabling it) and will allow the native stubbing in Cypress to work without any alterations.
Cypress.Commands.overwrite('visit', (originalFn, url, options) => {
const opts = Object.assign({}, options = {}, {
onBeforeLoad: (window, ...args) => {
window.fetch = null;
if (options.onBeforeLoad) {
return options.onBeforeLoad(window, ...args);
}
},
});
return originalFn(url, opts);
});

How can I cache data from API to Cache Storage in React PWA?

I built a Progressive Web App with ReactJS and have an issue. I am using mockApi to fetch the data.
When offline, my app doesn't work since the service worker only caches static assets.
How can I save HTTP GET calls from mockApi into the cache storage?
Along with your static assets, you can define which URLs do you want to cache:
var CACHE_NAME = 'my-cache_name';
var targetsToCache = [
'/styles/myStyles.scss',
'www.stackoverflow.com/'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
return cache.addAll(targetsToCache);
})
);
});
Then you have to instruct your service worker to intercept the network requests and see if there is a match with the addresses in the targetsToCache:
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
// This returns the previously cached response
// or fetch a new once if not already in the cache
return response || fetch(event.request);
})
);
});
I wrote a series of articles about Progressive Web Apps if you are interested in learning more about it.

How to receive notifications from Firebase in window's context (as well as service worker)

I have a react app with the following in firebase-messaging-sw.js in public folder of the app:
importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
'messagingSenderId': '<my-sender-id>'
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Do some stuff
});
And in my index.js file I have this:
import * as serviceWorker from './serviceWorker';
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
console.log( registration);
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
} else {
console.log('Unable to get permission to notify.');
}
});
}).catch(function(err) {
console.log('Service worker registration failed, error:', err);
});
}
I can publish a message and get a notification if the window is not active. So far, so good.
However, I also need to get the notification if the window is active. I try adding this to the service worker:
// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
// `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// ...
});
...but I get this error from firebase:
errors.ts:101 Uncaught FirebaseError: Messaging: This method is available in a Window context. (messaging/only-available-in-window).
It seems that the above javascript needs to go into the index.js file so that it is processed in the window context (all of the questions I have seen on this just say "the onMessage call need to be in the foreground app").
BUT then I don't have access to the messaging variable declared in the service worker.
Whats the correct way to do this? Surely I shouldn't be initialising firebase twice?
Only the setBackgroundMessageHandler()-method must be called in the serviceworker.
You need to use the onMessage() handler in the javascript-files of your Application-UI to do further actions with the payload.
Take a close look at the docs.

How to cache React application in service worker

I'm trying to create a React PWA from scratch. So far my project outputs the minified files to a dist/js folder.
In my service worker file I'm using Workbox to precache the app. This is my setting so far:
importScripts("./node_modules/workbox-sw/build/workbox-sw.js");
const staticAssets = [
"./",
"./images/favicon.png",
]
workbox.precaching.precacheAndRoute(staticAssets);
Currently if I enable offline from dev tools > Service Workers, it throws these errors and the app fails to load:
3localhost/:18 GET http://localhost:8080/js/app.min.js net::ERR_INTERNET_DISCONNECTED
localhost/:1 GET http://localhost:8080/manifest.json net::ERR_INTERNET_DISCONNECTED
3:8080/manifest.json:1 GET http://localhost:8080/manifest.json net::ERR_INTERNET_DISCONNECTED
logger.mjs:44 workbox Precaching 0 files. 2 files are already cached.
5:8080/manifest.json:1 GET http://localhost:8080/manifest.json net::ERR_INTERNET_DISCONNECTED
How can I fix this?
this means your resources are not getting cached properly,
you need to add them to cache before accessing,
workbox by default do it for you.
it shows 2 files cached, as they present in your array, expected result
same do it for all remaining too.
const staticAssets = [
"./",
"./images/favicon.png",
"./js/app.min.js",
"./manifest.json",
{ url: '/index.html', revision: '383676' }
]
you can try to add eventlistener,
self.addEventListener('install', event => {
console.log('Attempting to install service worker and cache static assets');
event.waitUntil(
caches.open("staticCacheName")
.then(cache => {
return cache.addAll(staticAssets);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(caches.match(event.request)
.then(function(response) {
if (response) {
return response;
}
return fetch(event.request);
})
);
});

Add Service Worker to Create React App Project

I am installing a notification system called Subscribers with a project built with create react app. They ask the developer to download their service worker and include it in the root directory of the project. I have never had to install / use a service worker before, which is most likely the root of my misunderstanding.
How do you add a service worker into the root directory of a React project? The instructions say the service worker should appear in the root directory as https://yoursite.com/firebase-messaging-sw.js. In an attempt to register that URL, I included a service worker under src/index.js:
import Environment from './Environment'
export default function LocalServiceWorkerRegister() {
const swPath = `${Environment.getSelfDomain()}/firebase-messaging-sw.js`;
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register(swPath).then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
}
In production, I receive a 404 error. I have tried placing the firebase-messaging-sw.js file in the root directory, and under the src folder. Same error each time.
Here are the instructions from Subscribers:
https://subscribers.freshdesk.com/support/solutions/articles/35000013054-diy-installation-instructions
The public folder is the provided 'escape hatch' for adding assets from outside of the module system.
From the docs:
If you put a file into the public folder, it will not be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the public folder, you need to use a special variable called PUBLIC_URL
So, once copied to the public folder, you would reference the file like this:
import Environment from './Environment'
export default function LocalServiceWorkerRegister() {
const swPath = `${process.env.PUBLIC_URL}/firebase-messaging-sw.js`;
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register(swPath).then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
}

Resources