jeudi 25 mars 2021

Ad a serviceworker that works offline on website

I am trying to implement a serviceworker that works offline on my website, Ive done some research but I cannot figure out whats going wrong and how I can fix it. But I get the error:

sw.js:1 Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'https://mydomain/cache-polyfill.js' failed to load.

Heres what Ive come up with this far, My serviceworker:

importScripts('/cache-polyfill.js');


self.addEventListener('install', function (e) {
    e.waitUntil(
        caches.open('airhorner').then(function (cache) {
            return cache.addAll([
                '/',
                '/Home/Index.cshtml',
                '/css/site.min.css',
                '/js/lottie.js',
                '/js/site.js'
            ]);
        })
    );
});

My cache-polyfill.js:

(function () {
    var nativeAddAll = Cache.prototype.addAll;
    var userAgent = navigator.userAgent.match(/(Firefox|Chrome)\/(\d+\.)/);

    // Has nice behavior of `var` which everyone hates
    if (userAgent) {
        var agent = userAgent[1];
        var version = parseInt(userAgent[2]);
    }

    if (
        nativeAddAll && (!userAgent ||
            (agent === 'Firefox' && version >= 46) ||
            (agent === 'Chrome' && version >= 50)
        )
    ) {
        return;
    }

    Cache.prototype.addAll = function addAll(requests) {
        var cache = this;

        // Since DOMExceptions are not constructable:
        function NetworkError(message) {
            this.name = 'NetworkError';
            this.code = 19;
            this.message = message;
        }

        NetworkError.prototype = Object.create(Error.prototype);

        return Promise.resolve().then(function () {
            if (arguments.length < 1) throw new TypeError();

            // Simulate sequence<(Request or USVString)> binding:
            var sequence = [];

            requests = requests.map(function (request) {
                if (request instanceof Request) {
                    return request;
                }
                else {
                    return String(request); // may throw TypeError
                }
            });

            return Promise.all(
                requests.map(function (request) {
                    if (typeof request === 'string') {
                        request = new Request(request);
                    }

                    var scheme = new URL(request.url).protocol;

                    if (scheme !== 'http:' && scheme !== 'https:') {
                        throw new NetworkError("Invalid scheme");
                    }

                    return fetch(request.clone());
                })
            );
        }).then(function (responses) {
            // If some of the responses has not OK-eish status,
            // then whole operation should reject
            if (responses.some(function (response) {
                return !response.ok;
            })) {
                throw new NetworkError('Incorrect response status');
            }

            // TODO: check that requests don't overwrite one another
            // (don't think this is possible to polyfill due to opaque responses)
            return Promise.all(
                responses.map(function (response, i) {
                    return cache.put(requests[i], response);
                })
            );
        }).then(function () {
            return undefined;
        });
    };

    Cache.prototype.add = function add(request) {
        return this.addAll([request]);
    };
}());

My default script file that registers the serviceworker:

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js', {
    }).then(function (registration) {
        // Registration was successful
        console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function (err) {
        // registration failed :(
        console.log('ServiceWorker registration failed: ', err);
    });
}

Thanks beforehand!! Best regards Max




Aucun commentaire:

Enregistrer un commentaire