0

我想跟蹤用戶在我的PWA中的活動。是否有可能發送一個請求到我的服務器上每個網站的印象與當前的URI?如何跟蹤服務人員中的當前URL更改?

場景:用戶使用當前URI打開PWA - >請求。 用戶打開一個子頁面 - >用當前URI發送請求。

我的例子服務worker.js:

var cacheName = 'weatherPWA-step-6-2'; 
var filesToCache = [ 
    '/', 
    '/index.html', 
    '/scripts/app.js', 
    '/styles/inline.css', 
    '/images/clear.png', 
    '/images/cloudy-scattered-showers.png', 
    '/images/cloudy.png', 
    '/images/fog.png', 
    '/images/ic_add_white_24px.svg', 
    '/images/ic_refresh_white_24px.svg', 
    '/images/partly-cloudy.png', 
    '/images/rain.png', 
    '/images/scattered-showers.png', 
    '/images/sleet.png', 
    '/images/snow.png', 
    '/images/thunderstorm.png', 
    '/images/wind.png' 
]; 

self.addEventListener('install', function(e) { 
    console.log('[ServiceWorker] Install'); 
    e.waitUntil(
    caches.open(cacheName).then(function(cache) { 
     console.log('[ServiceWorker] Caching app shell'); 
     return cache.addAll(filesToCache); 
    }) 
); 
}); 

self.addEventListener('activate', function(e) { 
    console.log('[ServiceWorker] Activate'); 
    e.waitUntil(
    caches.keys().then(function(keyList) { 
     return Promise.all(keyList.map(function(key) { 
     if (key !== cacheName) { 
      console.log('[ServiceWorker] Removing old cache', key); 
      return caches.delete(key); 
     } 
     })); 
    }) 
); 
    return self.clients.claim(); 
}); 

self.addEventListener('fetch', function(e) { 
    console.log('[ServiceWorker] Fetch', e.request.url); 
    console.log("Url", Client.url); 
    e.respondWith(
    caches.match(e.request).then(function(response) { 
     return response || fetch(e.request); 
    }) 
); 
}); 
+0

你可以聽窗口上的'hashchange'事件並做任何你想做的事情。 –

+0

@JPrakash:謝謝! – CYGS

回答

0

這個問題也許應該表述是這樣的:

我怎麼可以跟蹤我的分析包中的網頁瀏覽時,文件被從緩存提供?

這是一個很好的問題,因爲您肯定會調整活動。

如果您只根據服務器日誌跟蹤活動,那麼您將需要每次執行一次網絡請求。這是一個低效率和老派的IMO。但如果這是你追蹤活動的方式,那麼就建立一個處理它的方法。您將需要構建一種人造AJAX方式來更新日誌。當然,你也可以使用它來保持你的緩存新鮮,在重新驗證策略時保持陳舊。

如果您使用的是Google Analytics等服務,那麼您將以編程方式觸發流量。關於這些服務的好處是你不需要改變任何東西來觸發它們的日誌記錄活動,因爲它們是從UI而不是服務器進行測量的。

如果您在消費者脫機時允許進行活動,那麼您需要對活動進行排隊,並在活動恢復聯機後進行重放。這是後臺同步API一旦得到廣泛支持就會有用的地方。

希望這會有所幫助。讓我知道你是否有更多的問題和澄清。