Offline mode doesn't work
xiaoouwang opened this issue · comments
Could you help with this issue?
At the beginnig of the chapter 2,
I have added the following code at the top of js/app.js file:
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("../serviceworker.js")
.then(function(registration) {
console.log("Service Worker registered with scope:", registration.scope);
}).catch(function(err) {
console.log("Service Worker registration failed:", err);
});
}
Then I am simulating an offline state in Chrome (also in Firefox and Safari). I do not see the error message but this one instead:
This site can’t be reached
localhost refused to connect.
Search Google for localhost 8443
ERR_CONNECTION_REFUSED
It is behaving simply as I am offline. Even removing these lines of code while I am offline gives me the same result.
Basicaaly i've juste copied the message here #5 since it seems that the author of this book never read the issues
Registering the service worker is just one part of the puzzle, after that you should modify the serviceworker.js
to respond properly.
The file should have the following (as int he Figure 2.8 in the book):
self.addEventListener("fetch", function (event) {
event.respondWith(
fetch(event.request).catch(function () {
return new Response(
"Welcome to the Gotham Imperial Hotel.\n" +
"There seems to be a problem with your connection.\n" +
"We look forward to telling you about our hotel as soon as you go online."
);
})
);
});
I agree with the original author - the example in chapter two does not work. I am trying to get the offline message to show up in Firefox but even when selecting offline mode, clearing everything out of the browser, unregistering the previously registered service worker, hitting Ctrl-C and then npm start, it still does not show the offline message on my screen. I have also tried to use Chrome in the way outlined in the book and i still cannot see the offline message. Here is my code in "serviceworker.js":-
var responseContent = "<html><body><style>body {text-align: center; background-color: #333; color: #eee;}</style><h1>Gotham Imperial Hotel</h1><p>There seems to be a problem with your connection.</p><p>Come visit us at 1 Imperial Plaza, Gotham City for free WiFi.</p></body></html>"
self.addEventListener("fetch", function(event) { event.respondWith( fetch(event.request).catch(function() { return new Response( responseContent, {headers: {"Content-Type": "text/html"}} ); }) ); });