# **Service Worker**
{%hackmd theme-dark %}
是AppCache 的前身,一段瀏覽器在後台運行的腳本,
讓一個功能不需要頁面或使用者操作就可以執行
*Can load contents even without internet connection
使用者不需要連網也可以取得資料*
... 客製化的 Not Found 404 頁面
... 當使用者處於斷線狀態並對貼文按讚時,等到網路恢復貼文就會被讚ed
* [參考資料](https://cythilya.github.io/2017/07/16/service-worker/)
* [MDN 文件](https://developer.mozilla.org/zh-CN/docs/Web/API/Service_Worker_API/Using_Service_Workers)
***
* [推送通知](https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web)
* [背景 Sync/Preload](https://developers.google.com/web/updates/2015/12/background-sync)
* [Google 文件](https://developers.google.com/web/fundamentals/primers/service-workers)
## !! Notice !!
> ### Can't manipulate DOM
> ### Unless on localhost or https required
> ### Do Support ES6 Promise
> ### A service worker has a lifecycle that is completely separate from your web page.
>
---
## Service Worker Life Cycle
>1. Register SW
>2. Install SW
>3. Activate Sw

**Google**

**MDN**

## Browser Support

---
## Regiseter Service Worker
>Mostly in main.js
```javascript=
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
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);
});
});
}
```
---
## Service Worker 支持的事件(event)

---
## **註冊 service worker 時 scope 的問題**
>Scope 為 Service Worker 的運作範圍。
>若沒有設定 Scope,運作範圍預設為整個 Domain;若有設定 Scope,則為這個資料夾之下。
>若沒有設定 Scope,因此整個 localhost 都可以使用。
>但若設定`navigator.serviceWorker.register('/serviceWorker.js', { scope: '/test/' })`,則限定只能運作於「localhost/test/」之下。
---
## Check Service Worker Status
* > url: ``` chrome://inspect/#service-workers ```
* > Inspect: ``` Application -> Service Workers```
---
## Install Service Worker
• install 事件要做的事情是啟動瀏覽器的離線快取能力 •
• 要先停止舊的 worker 才能執行新的 •
1. Open a Cache
> ``` var CACHE_NAME = 'v1'; // 通常命名為版本號 ex. 'v1'```
2. Cache Files
```javascript=
var urlsToCache = [
'/',
'/styles/main.css',
'/script/main.js'
]
```
3. Confirm whether all the required assets are cached or not
```javascript=
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
// Open a Cache with caches.open()
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
// Add Cache Files From urlsToCache
// add 的檔案就是讓使用者離線也可以使用
return cache.addAll(urlsToCache);
})
);
});
```
##### waitUntil() Methods
> Takes a promise and uses it to know how long installation takes, and whether it succeeded or not.
> >用來確定 SW 需要安裝的時間與成功與否
> >所有需要被 cache 的檔案 cache 成功後才算完成 SW 的安裝
> >urlsToCache 的檔案越多 安裝的時間需要的越久 成功的機率也低,所以決定要預先 cache 的檔案時要好好考慮是不是一定要放近來
> > ```event.waituntil(aPromise)```
> Google 文件說明
>
## After Loading Page
> Service Worker 開始接收 fetch event 並回傳結果
```javascript=
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
```
### Update Cache Storage
>### 更新流程
>1. > Update your service worker JavaScript file. When the user navigates to your site, the browser tries to redownload the script file that defined the service worker in the background. If there is even a byte's difference in the service worker file compared to what it currently has, it considers it new.
>2. >Your new service worker will be started and the install event will be fired.
>3. > At this point the old service worker is still controlling the current pages so the new service worker will enter a ```waiting``` state.
>4. > When the currently open pages of your site are closed, the old service worker will be killed and the new service worker will take control.
>5. > Once your new service worker takes control, its ```activate``` event will be fired.
----
> ## 用 Avtivate 的原因
> 刪除舊 cache 是在 install 時,所有舊的 cache 將會被清除 即無法再 serve file from cache(舊) --> 無法再從緩存中提供文件
> Google 說明:

----
### 作法 1
> loop 目前存在的 cache 如果有名字與新的不同時 delete 該筆cache
```javascript=
// Call Activate Event
self.addEventListener('activate', e => {
console.log('Service Worker: Activated');
// Remove unwanted caches
e.waitUntil(
caches.keys().then(CACHE_NAME => {
return Promise.all(
CACHE_NAME.map(cache => {
if (cache !== CACHE_NAME) {
console.log('Service Worker: Clearing Old Cache');
return caches.delete(cache);
}
})
);
})
);
});
```
---
### 作法2
> 創建一個 white list,刪除任何不在白名單的緩存
```javascript=
self.addEventListener('activate', function(event) {
var cacheWhitelist = ['pages-cache-v1', 'blog-posts-cache-v1'];
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
```
#### cache v1 --- OLD cache
>```const CACHE_NAME = 'v1';```
> before

### cache v1 --- NEW cache
> ```javascript=
> const CACHE_NAME = 'v2'
>after

***cached files***
```javascript=
const urlsToCache = [
'index.html',
'about.html',
'/css/style.css',
'/js/main.js'
];
```
**Storage Data**


# 可能會遇到的問題
* 安裝失敗不會告知原因:
> 如果service worker註冊後未在 `chrome://inspect/#service-workers` 或 `chrome://serviceworker-internals` 中顯示,則有可能是引發錯誤或向 `event.waitUntil()` 發送被拒絕的 promise 而導致無法安裝
* Google Soloution
> 要解決該問題,請轉至 `chrome://serviceworker-internals` 並選中“Open DevTools window and pause JavaScript execution on service worker startup for debugging”,然後將調試程序語句置於安裝事件開始處。這與[未捕獲異常中的暫停](https://developers.google.com/web/tools/chrome-devtools/javascript/add-breakpoints#exceptions)共同揭露問題。
* MDN Solution
> service worker文件的地址没有写对— 需要相对于 origin , 而不是 app 的根目录。在我们的例子例, service worker 是在 `https://mdn.github.io/sw-test/sw.js`,app 的根目录是 `https://mdn.github.io/sw-test/`。应该写成 `/sw-test/sw.js` 而非 `/sw.js`.
## fetch() 注意事項
> 請求中若需要包含 coolkie 等憑據 則需使用
```javascript=
fetch(url, {credentials: 'include'})
```
## worker 推播的各種狀態

---
**2020-06-02**