0
votes

I haven't been able to get Google Analytics to work offline. I have a service worker:

if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('js/OfflineGoogleAnalytics.js')
            .then(function (registration) {
                console.log('Registered:', registration);
            })
            .catch(function (error) {
                console.log('Registration failed: ', error);
            });
    });
}

The service worker registers code in a separate JavaScript file which contains:

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.3.1/workbox-sw.js');
workbox.googleAnalytics.initialize();

I followed these instructions: https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics

I am running an asp.net core website from visual studio. I run the website with an internet connection so it's able to launch online. Then I disable all of my network adapters to simulate an offline mode and I navigate around the various pages. Next I reenable the network adapters to reenable internet access and I navigate around a bit more.

The offline page views are never sent to Google Analytics and I don't see them show up in the Google Analytics Dashboard.

Also, in Chrome's developer tools I can see that the service worker is running and there are no errors in the console.

Is there anything else I need to do to get offline Google Analytics working?

1

1 Answers

0
votes

I finally got it working. I believe there was an issue with the service worker's scope. In Chrome Dev Tools the service worker never had any 'Clients' listed. I moved the service worker registration and file up a level and set the scope to '/'.

        if ('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
            navigator.serviceWorker.register('OfflineGoogleAnalytics.js', { scope: '/' })
                .then(function (registration) {
                    console.log('Registered:', registration);
                })
                .catch(function (error) {
                    console.log('Registration failed: ', error);
                });
        });
    }