So you're a Noob? Post your questions here until you graduate! Don't be shy.

User avatar
By stayzeef
#85653 Hello everyone!

I'm working on a 3d printed wifi car running on a Nodemcu (not too sure of the exact board as i got it for dirt cheap on eBay).

I'm getting the following error:
An unknown error occurred when fetching the script.
Service worker registration failed: DOMException: Failed to register a ServiceWorker for scope ('https://192.168.1.223/') with script ('https://192.168.1.223/service-worker.js'): An unknown error occurred when fetching the script.

When i go to https://192.168.1.223/service-worker.js I do see the code within the file, so it's being presented just fine. It seems that this script is unable to access /service-worker.js as manifest.json is being loaded just fine.
Code: Select all<script>
if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('service-worker.js')
      .then(reg => {
        console.log('Service worker registered!', reg);
      })
      .catch(err => {
        console.log('Service worker registration failed: ', err);
      });
  });
}
</script>

I've tried this in incognito tabs, set all kinds of chrome flags, and cleared my cache/unregistered service worker more times than i can count.

The code on the Nodemcu is as followed(removed car logic):
Code: Select all#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServerSecure.h>
#include <ESP8266mDNS.h>

#ifndef STASSID
#define STASSID "XXXXXXX"
#define STAPSK  "XXXXXXX"
#endif

const char html_index[] = {index.html code in C-string - see below};
const char offline_html[] = {offline.html code in C-string - did not include below};
const char manifest_js[] = {manifest.json code in C-string - see below};
const char serviceWorker_js[] = {service-worker.js code in C-string - see below};
const char tesla_192_png[] PROGMEM= {**hex for picture**};
const char tesla_512_png[] PROGMEM= {**hex for picture**};

const char* ssid = STASSID;
const char* password = STAPSK;

static const uint8_t x509[] PROGMEM = {  #include "x509.h"};
static const uint8_t rsakey[] PROGMEM = {  #include "key.h"};

ESP8266WebServerSecure server(443);

void setup(void)
{
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.setServerKeyAndCert_P(rsakey, sizeof(rsakey), x509, sizeof(x509));

  server.on("/", handleRoot);
  server.on("/index.html",handleIndex);
  server.on("/service-worker.js",handleServiceWorker);
  server.on("/offline/offline.html",handleOffline);
  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTPS server started");
}

void loop(void)
{
  server.handleClient();
  MDNS.update();
}

void handleRoot()
{
  server.sendHeader("Location","/index.html");
  server.send(303);
}

void handleIndex()
{
  server.send(200,"text/html",html_index);
}

void handleNotFound() {
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

void handleOffline()
{
  server.send(200, "text/html",offline_html);
}
void handleManifest()
{
  server.send(200,"application/js",manifest_js);
}

void handleServiceWorker()
{
  server.send(200,"application/js",serviceWorker_js);
}

The Index.html is as followed (on the Nodemcu code this is converted to C-string):
Code: Select all<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://cdn.materialdesignicons.com/2.5.94/css/materialdesignicons.min.css">
<script src="https://kit.fontawesome.com/fef9c30a7a.js" crossorigin="anonymous"></script>
<meta name="mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width, user-scalable=no">
<head>
    <link rel="manifest" href="/manifest.json">
    <meta name="theme-color" content="#4285f4" />
    <title>Tesla Truck Control</title>
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"> </script>
    <style>
       **CSS removed for easy reading - planning on making it a separate file**
    </style>
</head>
<body>
  **body removed for easy reading**
<script>
if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('service-worker.js')
      .then(reg => {
        console.log('Service worker registered!', reg);
      })
      .catch(err => {
        console.log('Service worker registration failed: ', err);
      });
  });
}
</script>
</body>
</html>

The manifest.json
Code: Select all{
  "short_name": "CyberTruck",
  "name": "Tesla Cyber Truck",
  "icons": [
    {
      "src": "/images/tesla_192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "/images/tesla_512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": "/",
  "display": "fullscreen",
  "background_color": "#3367D6"
}

And finally, the actual service-worker.js. This was copied directly from the Google codelabs with minor changes. I haven't gotten around to actually modifying this part. I have tried different versions from empty to fully redirecting to the offline.html page but nothing made a difference.
Code: Select allconst cacheName = 'cache-v1';
const precacheResources = [
  '/',
  'index.html',
  'offine/offline.html'
];

self.addEventListener('install', event => {
  console.log('Service worker install event!');
  event.waitUntil(
    caches.open(cacheName)
      .then(cache => {
        return cache.addAll(precacheResources);
      })
  );
});

self.addEventListener('activate', event => {
  console.log('Service worker activate event!');
});

self.addEventListener('fetch', event => {
  console.log('Fetch intercepted for:', event.request.url);
  event.respondWith(caches.match(event.request)
    .then(cachedResponse => {
        if (cachedResponse) {
          return cachedResponse;
        }
        return fetch(event.request);
      })
    );
});