Service worker makes js run twice - javascript

I implemented the service worker from pwabuilder.com and it works just fine
The problem is that the service worker runs even if the browser is online, so every js functions runs twice, one from the service worker and one from my other js files
Should I look if it's an active service worker before I run my js functions or should I somehow make sure that the service worker is not running when the browser is online?
This is the code I run in my main index file
if (navigator.serviceWorker.controller) {
//console.log('[PWA Builder] active service worker found, no need to register')
} else {
//Register the ServiceWorker
navigator.serviceWorker.register('pwabuilder-sw.js', {
scope: './'
}).then(function (reg) {
//console.log('Service worker has been registered for scope:' + reg.scope);
});
}
The pwabuilder-sw.js looks like this:
self.addEventListener('install', function (event) {
var indexPage = new Request('');
event.waitUntil(
fetch(indexPage).then(function (response) {
return caches.open('pwabuilder-offline').then(function (cache) {
//console.log('[PWA Builder] Cached index page during Install' + response.url);
return cache.put(indexPage, response);
});
}));
});
//If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener('fetch', function (event) {
var updateCache = function (request) {
return caches.open('pwabuilder-offline').then(function (cache) {
return fetch(request).then(function (response) {
//console.log('[PWA Builder] add page to offline' + response.url);
return cache.put(request, response);
});
});
};
event.waitUntil(updateCache(event.request));
event.respondWith(
fetch(event.request).catch(function (error) {
//Check to see if you have it in the cache
//Return response
//If not in the cache, then return error page
return caches.open('pwabuilder-offline').then(function (cache) {
return cache.match(event.request).then(function (matching) {
var report = !matching || matching.status === 404 ? Promise.reject('no-match') : matching;
return report;
});
});
})
);
});

Service Workers are meant to work all the time once registered, installed and activated
Service workers are event driven and their primary use is to act as a caching agent, to handle network requests and to store content for offline use. Secondly to handle push messaging.
I trust you understand that in order to act as a caching agent the service worker will run regardless if the application is online or offline. You have various caching scenarios to consider.
It is hard to provide exact solution for the mentioned: 'every js functions runs twice'.I doubt that all JS functions would always run twice. It seems this is implementation dependant.
Service workers cannot have a scope above their own path, by default it will control all resources below the scope of the service worker, this scope can also be restricted.
navigation.serviceWorker.register(
'/pwabuilder-sw.js', { //SW located at the root level here
scope: '/app/' //to control all resource accessed form within path /app/
}
);
I believe that the script from pwabuilder.com does attempt to cache all resources even resources that should not be cached such as POST requests. You may need to modify the caching policy depending on what type of resources your are using.
There is no simple solution here and no easy answer can be provided.
In general you can use the service worker to cache resources in one of the following ways:
Cache falling back to network
self.addEventListener('fetch', (event) => {
event.responseWith(
caches.match(event.request)
.then((response) => {
return response || fetch(event.request);
})
);
});
Network falling back to cache
//Good for resources that update frequently
//Bad for Intermittend and slow connections
self.addEventListener('fetch', (event) => {
event.responseWith(
fetch(event.request).catch(() => {
return caches.match(event.request);
})
);
});
Cache then network
//Cache then network(1) (send request to cache and network simultaneousely)
//show cached version first, then update the page when the network data arrives
var networkDataReceived = false;
var networkUpdate = fetch('/data.json')
.then((response) => {
return response.json();
}).then((data) => {
networkDataReceived = true;
updatePage(data);
});
//Cache then network(2)
caches.match('/data.json')
.then ((response) => {
return response.json();
}).then((data) => {
if (!networkDataReceived) {
updatePage(data);
}
}).catch(() => {
return networkUpdate;
});
Generic fallback
self.addEventListener('fetch', (event) => {
event.responseWith(
caches.match(event.request)
.then((response) => {
return response || fetch(event.request);
}).catch(() => {
return caches.match('offline.html');
})
)
});
I hope the above helps at least a little find the exact issue you are facing. Cheers and happy codding!

React added this React.strictMode HOC that runs twice certain parts of the application, like class component constructor, render, and shouldComponentUpdate methods.
Check the docs:
https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects.
See if you have <React.StrictMode> at the top of your index.js file and if so, you might want to run a test without it.

Related

Service Worker - how to know whether cache cleared?

I'm trying to implement a basic service worker to assure that users of my simple web app have the latest code. So when I update html, js, or css files I can increment the cachename in the service worker file and prompt users to refresh, clear their cache, and get the latest code.
Until now I've relied on hacky ways to update javascript files (including a parameter in the referring URL: /javascript-file.js?v=1).
The with the service worker code below seem unpredictable: sometimes small changes to JS or CSS are reflected after I increment the cachename (code below). Sometimes the changes are reflected without incrementing the cachename, which suggests the code is ALWAYS pulling from the network (wasting resources).
How can you troubleshoot which version of files the code is using and whether the service worker is using cached or network versions? Am I not understanding the basic model for using service workers to achieve this goal?
Any help appreciated.
serv-worker.js (in root):
console.log('Start serv-worker.js');
const cacheName = '3.2121';
var urlsToCache = [
'home.html',
'home-js.js',
'web-bg.js',
'css/main.css',
'css/edit-menus.css'
];
self.addEventListener('install', event => {
console.log('Install event...', urlsToCache);
event.waitUntil(
caches.open(cacheName)
.then(function(cache) {
console.log('Opened cache', cacheName);
return cache.addAll(urlsToCache);
})
);
});
// Network first.
self.addEventListener('fetch', (event) => {
// Check the cache first
// If it's not found, send the request to the network
// event.respondWith(
// caches.match(event.request).then(function (response) {
// return response || fetch(event.request).then(function (response) {
// return response;
// });
// })
// );
event.respondWith(async function() {
try {
console.log('aPull from network...', event.request);
return await fetch(event.request);
} catch (err) {
console.log('aPull from cache...', event.request);
return caches.match(event.request);
}
}());
});
self.addEventListener('message', function (event) {
console.log('ServiceWorker cache version: ', cacheName, event);
console.log('Received msg1: ', event.data);
if (event.data.action === 'skipWaiting') {
console.log('ccClearing cache: ', cacheName);
// caches.delete('1.9rt1'); // hardcode old one
// caches.delete(cacheName); // actually removes cached versions
caches.keys().then(function(names) {
for (let name of names)
caches.delete(name);
});
self.skipWaiting();
}
});
Code in web-bg.js, which home.html references:
function servWorker(){
let newWorker;
function showUpdateBar() {
console.log('Show the update mssgg...ddddd');
$('#flexModalHeader').html('AP just got better!');
$('#flexModalMsg').html("<p>AP just got better. Learn about <a href='https://11trees.com/support/release-notes-annotate-pro-web-editor/'>what changed</a>.<br><br>Hit Continue to refresh.</p>");
$('#flexModalBtn').html("<span id='updateAPbtn'>Continue</span>");
$('#flexModal').modal('show');
}
// The click event on the pop up notification
$(document).on('click', '#updateAPbtn', function (e) {
console.log('Clicked btn to refresh...');
newWorker.postMessage({ action: 'skipWaiting' });
});
if ('serviceWorker' in navigator) {
console.log('ServiceWORKER 1234');
navigator.serviceWorker.register(baseDomain + 'serv-worker.js').then(reg => {
console.log('In serviceWorker check...', reg);
reg.addEventListener('updatefound', () => {
console.log('A wild service worker has appeared in reg.installing!');
newWorker = reg.installing;
newWorker.addEventListener('statechange', () => {
// Has network.state changed?
console.log('SSState is now: ', newWorker.state);
switch (newWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
// new update available
console.log('Detected service worker update...show update...');
showUpdateBar();
}
// No update available
break;
}
});
});
});
let refreshing;
navigator.serviceWorker.addEventListener('controllerchange', function (e) {
console.log('a1111xxxListen for controllerchange...', e);''
if (refreshing) return;
console.log('Refresh the page...');
window.location.reload();
refreshing = true;
});
} // End serviceworker registration logic
return;
} // END serv-worker
You've commented out the section for /// Check the cache first and then below that the try/catch statement again pulls from the network and falls back to the cache.
Uncomment this section of code and see if you're loading from the cache first.
// event.respondWith(
// caches.match(event.request).then(function (response) {
// return response || fetch(event.request).then(function (response) {
// return response;
// });
// })
// );
Don't forget that even if you request from the network from the service worker the browser will still use it's own internal cache to serve data. How long the data stays in the browser's cache depends on the expiration headers being sent by the server.
When using expires, it's still a fairly common solution to do something like:
index.html - expires after an hour. Has script/css tags that call out file names with ?v=x.y.z
/resources - folder that holds js and css. This folder has a very long expiration time. But that long expiration is short circuited by changing the ?v=x.y.z in index.html
I've used the above successfully in Progressive Web Apps (PWAs). But it is a little painful when debugging. The best option here is to manually clear out the cache and service worker from Dev Tools \ Application, if you're in Chrome.

How to respond to fetch event for a navigation in service worker?

I have created a SPA (Single Page Application) with Create-React-App. I added a service worker to it so that the SPA could load when there is no network connection. The service worker successfully caches all the resources but fails respond when there is no network connection. I've tried many things but just couldn't get it to serve the assets to get offline capabilities. It gives the following error message:
Uncaught (in promise) TypeError: Failed to fetch
My service worker registers successfully and also caches assets successfully. Service Worker code:
const thingsToCache = [
'index.html',
'static/js/1.cb2fedf5.chunk.js',
'static/js/main.5e7fdc75.chunk.js',
'static/js/runtime~main.229c360f.js',
'static/css/main.ca6d346b.chunk.css',
'static/media/roboto.18d44f79.ttf',
'static/media/comfortaa.7d0400b7.ttf',
];
this.addEventListener('install', event => {
event.waitUntil(
caches.open('v1').then(cache => {
return cache.addAll(thingsToCache);
})
);
});
this.addEventListener('fetch', event => {
//respond to fetch requests here
caches
.match(event.request)
.then(cachedRes => {
if (cachedRes) {
event.respondWith(cachedRes);
} else {
throw new Error('No match found in cache!');
}
})
.catch(() => {
return fetch(event.request);
});
});
If you need the assets, then here's the link:
https://github.com/Twaha-Rahman/pwa-problem-assets
Thanks for all of your help!
You have an error in your fetch event listener. You need to call event.respondWith instead of event.waitUntil and it has to be at the top level. See below for a slighly amended version.
this.addEventListener('fetch', event => {
event.respondWith(
caches
.match(event.request)
.then(cachedRes => {
if (cachedRes) {
return cachedRes;
} else {
throw new Error('No match found in cache!');
}
})
.catch(() => {
return fetch(event.request);
});
)
});
More details: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers

Responding to fetch request via cache xor indexedDB

I am trying to have a service worker respond to fetch events depending on the type of request made. For static resources I use cache:
// TODO: make cache update when item found
const _fetchOrCache = (cache, request) => {
return cache.match(request).then(cacheResponse => {
// found in cache
if (cacheResponse) {
return cacheResponse
}
// has to add to cache
return fetch(request)
.then(fetchResponse => {
// needs cloning since a response works only once
cache.put(request, fetchResponse.clone())
return fetchResponse
});
}).catch(e => { console.error(e) })
}
for api responses I have already wired up IndexedDB with Jake Archibald's IndexedDB Promised to return content like this:
const fetchAllItems = () => {
return self.idbPromise
.then(conn => conn.transaction(self.itemDB, 'readonly'))
.then(tx => tx.objectStore(self.itemDB))
.then(store => store.getAll())
.then(storeContents => JSON.stringify(storeContents));
}
when I call everything in the service worker the cache part works, but the indexedDB fails miserably throwing an error that it cannot get at the api url:
self.addEventListener("fetch", event => {
// analyzes request url and constructs a resource object
const resource = getResourceInfo(event.request.url);
// handle all cachable requests
if (resource.type == "other") {
event.respondWith(
caches.open(self.cache)
.then(cache => _fetchOrCache(cache, event.request))
);
}
// handle api requests
if (resource.type == "api") {
event.respondWith(
new Response(fetchAllItems());
);
}
});
My questions would be as follows:
1.) Is there any point in separating storing fetch requests like this?
2.) How do I make the indexedDB part work?
good catch on using Jake Archibalds promise based idb. There are many ways to install his idb. The quickest - download the idb.js file somewhere(this is the library). Then import it on the first line in the service worker likeso:
importScripts('./js/idb.js');
.....
//SW installation event
self.addEventListener('install', function (event) {
console.log("[ServiceWorker] Installed");
});
//SW Actication event (where we create the idb)
self.addEventListener('activate', function(event) {
console.log("[ServiceWorker] Activating");
createIndexedDB();
});
.....
//Intercept fetch events and save data in IDB
.....
//IndexedDB
function createIndexedDB() {
self.indexedDB = self.indexedDB || self.mozIndexedDB || self.webkitIndexedDB || self.msIndexedDB;
if (!(self.indexedDB)) { console.console.log('IDB not supported'); return null;}
return idb.open('mydb', 1, function(upgradeDb) {
if (!upgradeDb.objectStoreNames.contains('items')) {
upgradeDb.createObjectStore('items', {keyPath: 'id'});
}
});
}
Judging by the code you pasted above to retrieve IDB data, it is unclear to me what exactly is idbPromise... Are you sure you declared this variable?
You should have something like this
importScripts('./js/idb.js');
//...
//createIdb and store
//...
var idbPromise = idb.open('mydb');
//and after that you have your code like idbPromise.then().then()...
So you create the IDB and the tables during the SW activation. After that you intercept the fetch events and start using the indexeddb like in the tutorials you've seen.
Good luck

ServiceWorker blocks any external resource

I've implemented ServiceWorker on some of my webapps to leverage offline capabilities and some other goodies related to the ServiceWorkers. Now, everything is working fine until I have added some external embedded scripts. There are about 3 external scripts that I've added on my webapp. Some of which fetch ads and display it on my app and some of which are used to gather analytics.
But, to my surprise, every external scripts are failing when the ServiceWorkers are enabled and throws below error in the console
I'm not sure why is this happening? Do I have to cache these scripts some way in ServiceWorker? Any help would be appreciated.
Here is my ServiceWorker code that I've added on my app.
importScripts('js/cache-polyfill.js');
var CACHE_VERSION = 'app-v18';
var CACHE_FILES = [
'/',
'index.html',
'js/app.js',
'js/jquery.min.js',
'js/bootstrap.min.js',
'css/bootstrap.min.css',
'css/style.css',
'favicon.ico',
'manifest.json',
'img/icon-48.png',
'img/icon-96.png',
'img/icon-144.png',
'img/icon-196.png'
];
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open(CACHE_VERSION)
.then(function (cache) {
console.log('Opened cache');
return cache.addAll(CACHE_FILES);
})
);
});
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request).then(function(res){
if(res){
return res;
}
requestBackend(event);
})
)
});
function requestBackend(event){
var url = event.request.clone();
return fetch(url).then(function(res){
//if not a valid response send the error
if(!res || res.status !== 200 || res.type !== 'basic'){
return res;
}
var response = res.clone();
caches.open(CACHE_VERSION).then(function(cache){
cache.put(event.request, response);
});
return res;
})
}
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys().then(function(keys){
return Promise.all(keys.map(function(key, i){
if(key !== CACHE_VERSION){
return caches.delete(keys[i]);
}
}))
})
)
});
Here's what I did to resolve the issue.
I tried checking if the app is online or not using Navigator.onLine API in the fetch event listener and if it's online, then serve the response from the server and from ServiceWorker otherwise. This way the requests won't get blocked while the app is online and thus resolves this particular issue.
Here's how I've implemented it.
self.addEventListener('fetch', function (event) {
let online = navigator.onLine;
if(!online){
event.respondWith(
caches.match(event.request).then(function(res){
if(res){
return res;
}
requestBackend(event);
})
)
}
});
You could also check the entire ServiceWorker script here: https://github.com/amitmerchant1990/notepad/blob/master/sw.js

Progressive web app Uncaught (in promise) TypeError: Failed to fetch

I started learning PWA (Progressive Web App) and I have problem, console "throws" error Uncaught (in promise) TypeError: Failed to fetch.
Anyone know what could be the cause?
let CACHE = 'cache';
self.addEventListener('install', function(evt) {
console.log('The service worker is being installed.');
evt.waitUntil(precache());
});
self.addEventListener('fetch', function(evt) {
console.log('The service worker is serving the asset.');
evt.respondWith(fromCache(evt.request));
});
function precache() {
return caches.open(CACHE).then(function (cache) {
return cache.addAll([
'/media/wysiwyg/homepage/desktop.jpg',
'/media/wysiwyg/homepage/bottom2_desktop.jpg'
]);
});
}
function fromCache(request) {
return caches.open(CACHE).then(function (cache) {
return cache.match(request).then(function (matching) {
return matching || Promise.reject('no-match');
});
});
}
I think this is due to the fact that you don't have a fallback strategy. event.respondWith comes with a promise which you have to catch if there's some error.
So, I'd suggest that you change your code from this:
self.addEventListener('fetch', function(evt) {
console.log('The service worker is serving the asset.');
evt.respondWith(fromCache(evt.request));
});
To something like this:
addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
if (response) {
return response; // if valid response is found in cache return it
} else {
return fetch(event.request) //fetch from internet
.then(function(res) {
return caches.open(CACHE_DYNAMIC_NAME)
.then(function(cache) {
cache.put(event.request.url, res.clone()); //save the response for future
return res; // return the fetched data
})
})
.catch(function(err) { // fallback mechanism
return caches.open(CACHE_CONTAINING_ERROR_MESSAGES)
.then(function(cache) {
return cache.match('/offline.html');
});
});
}
})
);
});
NOTE: There are many strategies for caching, what I've shown here is offline first approach. For more info this & this is a must read.
I found a solution to the same error, in my case the error showed when the service worker could not find a file*, fix it by following the network in dev tool of chrome session, and identified the nonexistent file that the service worker did not find and removed array of files to register.
'/processos/themes/base/js/processos/step/Validation.min.js',
'/processos/themes/base/js/processos/Acoes.min.js',
'/processos/themes/base/js/processos/Processos.min.js',
'/processos/themes/base/js/processos/jBPM.min.js',
'/processos/themes/base/js/highcharts/highcharts-options-white.js',
'/processos/themes/base/js/publico/ProcessoJsController.js',
// '/processos/gzip_457955466/bundles/plugins.jawrjs',
// '/processos/gzip_N1378055855/bundles/publico.jawrjs',
// '/processos/gzip_457955466/bundles/plugins.jawrjs',
'/mobile/js/about.js',
'/mobile/js/access.js',
*I bolded the solution for me... I start with just a file for cache and then add another... till I get the bad path to one, also define the scope {scope: '/'} or {scope: './'} - edit by lawrghita
I had the same error and in my case Adblock was blocking the fetch to an url which started by 'ad' (e.g. /adsomething.php)
In my case, the files to be cached were not found (check the network console), something to do with relative paths, since I am using localhost and the site is inside a sub-directory because I develop multiple projects on a XAMPP server.
So I changed
let cache_name = 'Custom_name_cache';
let cached_assets = [
'/',
'index.php',
'css/main.css',
'js/main.js'
];
self.addEventListener('install', function (e) {
e.waitUntil(
caches.open(cache_name).then(function (cache) {
return cache.addAll(cached_assets);
})
);
});
To below: note the "./" on the cached_assets
let cache_name = 'Custom_name_cache';
let cached_assets = [
'./',
'./index.php',
'./css/main.css',
'./js/main.js'
];
self.addEventListener('install', function (e) {
e.waitUntil(
caches.open(cache_name).then(function (cache) {
return cache.addAll(cached_assets);
})
);
});
Try to use / before adding or fetching any path like /offline.html or /main.js
Cached files reference should be correct otherwise the fetch will fail. Even if one reference is incorrect the whole fetch will fail.
let cache_name = 'Custom_name_cache';
let cached_files = [
'/',
'index.html',
'css/main.css',
'js/main.js'
];
// The reference here should be correct.
self.addEventListener('install', function (e) {
e.waitUntil(
caches.open(cache_name).then(function (cache) {
return cache.addAll(cached_files);
})
);
});

Categories

Resources