Unable to store simple HTML file using service worker

I am working on a webpage that displays a message when the user is offline. However, I am facing an issue with my service worker while trying to cache the page. The Chrome console always throws this error:

service-worker.js?v=1:1 Uncaught (in promise) DOMException: Quota exceeded. Promise rejected (async) addEventListener.event @ service-worker.js?v=1:10

Here is the code snippet for service worker registration:

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./assets/app/js/service-worker.js?v=1').then(function(registration) {
    // Registration was successful
    console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function(err) {
    // registration failed :(
    console.log('ServiceWorker registration failed: ', err);
});}

Below is the script for the service worker:

 'use strict';

var cacheVersion = 1;
var currentCache = {
    offline: 'offline-cache' + cacheVersion
};
var offlineUrl = '../../../offline.html';

this.addEventListener('install', event => {
    event.waitUntil(
        caches.open(currentCache.offline).then(function (cache) {
            return cache.addAll([
                offlineUrl
            ]);
        })
    );
});


this.addEventListener('fetch', event => {

    if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
        event.respondWith(
            fetch(event.request.url).catch(error => {
                return caches.match(offlineUrl);
            })
        );
    }
    else {
        event.respondWith(caches.match(event.request)
            .then(function (response) {
                return response || fetch(event.request);
            })
        );
    }
});

The content of offline.html:

<div> offline test </div>

I have tried deleting all caches but still receive the "Quota exceeded" error. Any suggestions or solutions? Thank you.

Answer №1

If you are looking to incorporate service workers into your production environment, I highly suggest using the sw-precache plugin (compatible with gulp or webpack) or workbox. Afterwards, you can configure cache file URLs within your bundler. For instance, here is an example utilizing webpack and sw-precache from a genuine project:

    new SWPrecacheWebpackPlugin(
        {
            cacheId: "static-cache",
            filepath:  __dirname + "/app/public/sw.js",
            stripPrefix: __dirname + "/app/public/",
            replacePrefix: "/",
            staticFileGlobs: [
                __dirname + "/app/public/dist/**/*.{js,html,css,eot,ttf,woff,woff2}",
                __dirname + "/app/public/img/**/*.{png,jpg,gif,svg}",
                __dirname + '/app/public/offline.html' /* define offline urls here */
            ],
            navigateFallback: __dirname + "/app/public/index.html"
        }
    )

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Facing challenges with using express.static() to display an image from a directory within my server on the front end

My application showcases various items on a specific page. Each item includes an image, number, and name. The images are stored in a folder named "uploads" on the backend. I can view the images within this folder, and from the Node backend, I'm provid ...

The functionality of a button within an AngularJS directive is not functioning as intended

I am trying to use a directive twice on one page. Inside the directive, there is a button that should toggle between showing the two directives when clicked. However, I'm encountering an issue where the values are not changing even though the ng-click ...

Storing POST Request Data in Express

I want to use a single API endpoint for both GET and POST requests. My goal is as follows: Send multiple POST requests to /api/users with data like: {'id': 2, is_valid: 'true'} Retrieve this data by fetching the same API URL later on ...

What could be causing the server to not successfully receive the ajax request?

I need to conduct integration tests on a website that routes all requests through a proxy: var express = require("express"), http = require("http"), port = (process.env.PORT || 8001), server = module.exports = express(), httpProxy = requir ...

Is it normal for Tailwind animation to loop twice when transitioning between pages in Next.js?

I'm currently utilizing react-hot-toast for displaying alerts and animating them during page transitions. The animation involves a double fade-in effect when transitioning between pages. In my project, I've integrated tailwindcss-animate within ...

Adding Logging Features in ASP.NET

I am currently working with an .ascx file that contains both JavaScript and div elements. I need to add a log statement inside a function for troubleshooting purposes. Can someone please guide me on how to achieve this? Below is a snippet of my code: fu ...

Guide to modify target blank setting in Internet Explorer 8

<a href="brochure.pdf" target="_blank" >Click here to download the brochure as a PDF file</a> Unfortunately, using 'target blank' to open links in a new tab is not supported in Internet Explorer 8. Are there any alternative solutio ...

jQuery Widget - Error: The method cannot be found in [object Object]

I am encountering an error when attempting to call my widget. Uncaught TypeError: Object [object Object] has no method 'koSpreadSheet' The plugin code: (function ($) { //Create spreadsheet app $.widget('koSpreadSheet', { ...

JavaScript libraries are not required when using the .append function to add HTML elements

Currently, I am attempting to utilize $.ajax in order to retrieve an html string from a php file and append it to the current html div. Oddly enough, when I use php echo, everything functions properly. However, when I attempt to load dynamically using $.lo ...

Using Jquery to dynamically add an active class to a link if it matches the current URL

Is there a way to modify the code below so that only the exact current URL will have the active class added? Currently, even when the URL is http://localhost/traineval/training, it also adds the active class to http://localhost/traineval/training/all_train ...

Proper method for adding elements in d3.js

I have a block of code that selects an #id and appends a svg-element into it: var graph = d3.select(elemId).append("svg") .attr('width', '100%') .attr('height', '100%') .append('g') Within th ...

Effective Strategies for Preserving Form Input Values during Validation Failure in Spring MVC

I am currently working on validating user input, and I want the user's input fields to be retained in case of any validation errors. This is how I have set up my input fields: <form:input path="firstName" class="text short" id="firstName" value=" ...

The website code lacks a dynamically generated <div> element

When using jQuery to dynamically add content to a "div" element, the content is visible in the DOM but not in the view page source. For example: <div id="pdf"></div> $("#btn").click(function(){ $("#pdf").html("ffff"); }); How can I ensur ...

Is it possible to apply CSS based on a component's displayName?

Are you a CSS pro? I'm attempting to apply a class that will make all descendants of an element read-only, but for some reason the style isn't being applied as expected: #ComponentDisplayName * { -webkit-user-select: text; -moz-user-sel ...

What is the method for determining the number of arrays contained within a file?

I am working with a JavaScript file that looks like this: // main.js let array1 = ['first array']; let array2 = ['second array']; Currently, I have two arrays declared in my main.js file. Is there a method to determine the total ...

Verifying the presence of a value within an SQL table

I am currently working on developing a bot that requires me to save the commandname and commandreply in a database. Right now, I am using mySQL Workbench for this task. My goal is to verify if the commandname provided by the user already exists in the tab ...

The UseEffect hook continues to run even if the dependency (router.query) remains the same

useEffect(() => { console.log('applying filter'); const updatedFilters = { status: { values: { label: router.query.status, value: router.query.status }, }, // Add additional filter properties here... }; ...

When utilizing React router v5, the exact property in a route may not function as expected if there is a

I am attempting to structure routes like Vue.js in an array format: // routes.js export const routing = [ { path: "/setting", component: Setting, }, { path: "/", co ...

Arranging an Array by Two Distinct Characteristics

I currently have an array that is grouped and sorted based on the "Program" attribute, which is working well. However, I now need to sort by a different attribute (Deliverable) within each group. Is this possible? If so, how can I achieve it? Below is an ...

Adjusting the size of text in KineticJS to ensure it fits comfortably within a rectangle while

Check out this link: http://jsfiddle.net/6VRxE/11/ Looking for a way to dynamically adjust text, text size, and padding to fit inside a rectangle and be vertically aligned? Here's the code snippet: var messageText = new Kinetic.Text({ x: .25* ...