I am new to web development so sorry if I'm not clear with my question.
I am trying to make a PWA and am currently testing to see if my manifest and service worker are working. In my project, I have an index.html file which calls the file app.js, in which I try to register the service worker named serviceworker.js. Here is the segment of code where I try to register my service worker:
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('/serviceworker.js')
.then(function() {
console.log('service worker registered');
});
}
else {
console.log('cannot register');
}
When I reload my page, my console displays "cannot register". To troubleshoot this, I wrote a line in the if clause to see if it was a problem with the condition itself. Turns out, Even by removing the if and else clauses and simply running the navigator.serviceWorker.register('/serviceworker.js')
.then(function() {
console.log('service worker registered');
});
segment of the code, the console displays an error say "cannot find property register". From what I understand, service workers do not work on all browsers, but I checked to see if it runs in Chrome (which is what I'm testing in) and it says that service workers are supported. Can someone please tell me why it isn't working? I'm currently using Version 80.0.3987.149 (Official Build) (64-bit) of Chrome. Alsi, I don't know if this is important, but I am using Node.js. Thanks in advance.
Cannot comment because of low reputation, but check this & this out.
In short:
Service workers requires the site using them to be served over HTTPS for security reasons,
but have execptions for localhost.
Check this for how to serve your html file on localhost.
Related
This is driving me crazy. I have been trying to implement push notifications for a website and I found a solution (Javacript API notification). The thing is: notifications are not working on mobile devices.
I read about service workers and I have been using this code to ask user for permission and everything, but it is still not working. I am not sure if I am doing something wrong or what. I read about it has to be an https site, but that's does not seem to be the problem. I have also tried the push.js plugin plugin.js, but no succeed so far (even when the demo of that plugin that it's in their website is working on my mobile browser) This is the website >>> https://park-inside.nl/test/
The "Set notification" button is meant to show a notification when the waiting time is below the selected time. So, to test this, just click "Set notification", then select minutes greater than the "Wachttijd" column and refresh page. The notification should appear. It works on desktop browser, but not on mobile. Any idea or suggestion? I would love and appreciate any help.
Note: I am using Chrome 94 on Android 9 (go)
Code that ask for user permission:
Notification.requestPermission(function(result) {
if (result === 'granted') {
navigator.serviceWorker.ready.then(function(registration) {
registration.showNotification('Notification with ServiceWorker');
});
}
});
See the browser support table for Web Notifications: https://caniuse.com/notifications.
They only work in Chrome on Android, not in the stock Android Browser.
Also, be sure to register a service worker, even if it's an empty one, as seen here: https://stackoverflow.com/a/31787926/10551293.
A demo of the notifications is available here: https://serviceworke.rs/push-payload_demo.html.
Google also has a step-by-step codelab available here: https://developers.google.com/codelabs/pwa-training/pwa03--going-offline#0
Apparently, I had to first do this to register a service worker:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js');
}
I am not really sure, but I was trying to use a route for the sw.js file, like this: js/sw.js. Once I placed that file in the root of the project, it worked.
Also, I added this code to that file to log some events to the console:
self.addEventListener('install', (event) => {
console.log('Installed');
});
self.addEventListener('activate', (event) => {
console.log('Activated');
});
self.addEventListener('fetch', (event) => {
console.log('Fetch request');
});
Thanks to swift-lynx for the links to some documentation, where I found a solution:
https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications
Very simply, I would like to disable the display of the repeated workbox messages that appear in my browser console while I am debugging. For instance, I don't need to see:
WorkBox: Using NetworkFirst to respond to '/fonts/KFOlCnqEu92Fr1MmEU9fBBc-.woff'
It clutters my FireFox console and it is something I dislike very much. If you like it, fine, please don't try to change my mind about the benefit of such useless (to me) messages.
Do you know how to turn it off?
For info sake, I am using Quasar and Vue to create a SPA - not even a PWA.
Thanks.
Simply add self.__WB_DISABLE_DEV_LOGS = true at the top of your service worker (sw.js) file.
Contrarily to what answers posted here say, the solution is not:
to unregister your service worker to get rid of the messages. Your app may need it to run properly
to add workbox.setConfig({debug: false}) unless knowing what it does:
it switches between a production build and a debug build. workbox automatically selects the debug build when running on localhost.
For me worked:
Console -> Application tab -> Service workers -> sw.js unregister
You can use workbox.setConfig({ debug: false }); in order to use production build and remove extra logging, otherwise adjust your web console log level filtering accordingly.
Doc : https://developers.google.com/web/tools/workbox/guides/troubleshoot-and-debug
You add this setting in your service worker definition file, after the import. For example:
importScripts(`https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js`);
if (workbox) {
console.log(`Yay! Workbox is loaded 😁`);
} else {
console.log(`Boo! Workbox didn't load 😬`);
}
// Switch debug logging on/off here. Default is on in dev and off in prod.
workbox.setConfig({debug: false});
For more information on this see https://developers.google.com/web/tools/workbox/guides/configure-workbox#configure_debug_builds_vs_production_builds
Thanks to the answer provided by Antonina K, I was able to locate an answer for FireFox. In case anyone else needs this. As Antonina mentioned, in Chrome, the console has an application tab that has references to all the service workers used by the browser. FireFox does not have the tab (or, at least my version does not).
In FireFox, open a new tab and place about:serviceworkers in the address bar. Scroll through the list to find the workbox service worker. For me, it was listed as localhost:8080. I deregistered that worker and I no longer see the multitude of workbox messages in my console. I can finally debug my app again!
Here is the link that I referenced to fix the problem:
Manage Service Workers in FireFox and Chrome
I'm training Progressive Web apps from Google labs, Here in a specific chapter there is to need setup the service worker script and check whether it will result the thing in console according to guidance provided in the lab instructions.
As I did all the instructions correctly,but the console returns empty whenever I reload the page to check whether the code is working.
Can any one tell me whats the actual problem with the code?
Google PWA training labs
And here is the code which Google code labs instructed me to do.
<script>
(function(){
'use strict';
// TODO - 2: Register the service worker
if (!('serviceWorker' in navigator)) {
console.log('Service worker not supported');
return;
}
navigator.serviceWorker.register('service-worker.js')
.then(function(registration){
console.log('Registered');
})
.catch(function(error) {
console.log('Registeration failed:', error);
});
})
</script>`
Note: The solution code(Provided from google) inside my local machine is working perfectly and service worker is registered, active , installed, and fetching.
So I'll keep this succinct: When trying to install, my service worker fails. This is all of my code in sw.js:
var cacheName = 'randomstring';
var filesToCache = [ '/' ];
self.addEventListener('install', function (e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName)
.then(function (cache) {
console.log('[ServiceWorker] About to fail');
return cache.addAll(filesToCache);
})
);
});
I get an exception because cache is undefined (on the cache.addAll bit).
Not really sure why this is the case?
I've used service workers before and never encountered this issue. This is my first time using a service worker with an ASP.Net back-end though, so not sure if that's the problem?
So, I figured this out. I was going to vote to close the question, but I figured I'd leave it here as I saw some other people with this issue who didn't know how to resolve it. Even though it's super-stupid :) (or more accurately, I am).
So I was running the website via the "Play" button, aka "Start Debugging", which, in Visual Studio 2017, launches a special Chrome window, in which the above error will be thrown.
To work around the issue, I can (or you can, internet traveller of the future) simply start without debugging, host the website in IIS, etc.
EDIT: If there's a better workaround where I can use the service worker in debug mode, please suggest it and I'll mark that as the answer. For my specific problem though, the above workaround is fine :).
Encountered the same problem and found some other ways.
VS recognises "chrome.exe" while debugging and adds some parameters, that´s why service workers won´t working.
There is an option Debug => Option => Debugging => General => Enable javascript debugging for asp.net (Chrome, Edge and FireFox). If you don´t want to use js debugging in vs - like me because i use chrome for js debugging - just deactivate this option and service workers will work.
VS Enable JS Debugging in Chrome
Alternatively you can add chrome as a new "browser" and switch the browser for debugging. Because vs recognise "chrome.exe" make a symlink via administative commandline "mklink chromedirect.exe chrome.exe" and add it as new browser in visual studio.
This can be done under the "Play" context menu => Browse with.
VS Play Context Menu
Just add chromedirect.exe without any arguments and a friendly name like "Google Chrome Direct". After that you can switch to the browsers and select if you want VS JS Debugging or not.
Some clients are failing to load the Google API in a production environment, but I'm not able to find anything wrong with my code.
Here's what I've got:
// Load Google's JavaScript Client API using requireJS !async plugin.
// You can learn more about the async plugin here: https://github.com/millermedeiros/requirejs-plugins/blob/master/src/async.js
define([
'async!https://apis.google.com/js/client.js!onload'
], function () {
'use strict';
console.log("googleAPI has loaded", window.gapi, window.gapi.client);
return window.gapi;
});
I've pulled this information from: Load async resource with requirejs timeout
The error message being displayed is:
Uncaught Error: Load timeout for modules:
async!https://apis.google.com/js/client.js!onload_unnormalized2,async!https://apis.google.com/js/client.js!onload
http://requirejs.org/docs/errors.html#timeout
This code doesn't produce any issues for me locally. It loads fine.
The first step I took to debug the issue was increasing the waitMinutes in requireConfig from 7 to 90. I thought maybe many people have very slow connections:
define(function () {
require.config({
baseUrl: 'js/',
enforceDefine: true,
// I'm seeing load timeouts on in googleAPI -- seeing if increasing wait time helps.
waitSeconds: 90,
...
});
});
This did not seem to affect the issue. I still see many clients reporting an issue.
What other debugging options are available to me in this scenario? Thanks
So I ran into a similar issue when trying debug my application in Internet Explorer 8, and maybe my experience is similar to your clients'.
For me, I found that I was receiving a timeout error because my test browser was having issues retrieving resources through https due to outdated root certificates. I do all of my Internet Explorer testing in a VM running windows 7. When I was trying to load my application I received the same error you mentioned in your post:
Uncaught Error: Load timeout for modules:
async!https://apis.google.com/js/client.js!onload_unnormalized2,async!https://apis.google.com/js/client.js!onload http://requirejs.org/docs/errors.html#timeout
I tried the url manually and was brought to a 'Untrusted Certificate' warning page on my browser. This confused me, but as I later found out the root certificates on my windows os were outdated and causing a failure with the https handshake. The async plug-in seems to consume the authentication exceptions and just sits waiting for something to magically go through leading to the timeout error.
The solutions I found to work are as follows:
Update the root certificates of the os
Change the security properties of my browser to not require certificate authentication
As for suggestions for further debugging, I have two ideas:
Try setting your browser's security properties as high as possible and see if you can recreate the issue (or just temporarily remove your local certificates)
Ask your clients to set their browser's security properties as low as possible, making sure to disable certificate authentication requirements, and ask them if they are still having problems. (If their problems go away, they might need to manually update their local certificates)