Giloo
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # **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 ![](https://i.imgur.com/X9GQiuQ.png) **Google** ![](https://i.imgur.com/bPGKKG5.png) **MDN** ![](https://i.imgur.com/LLtHTLs.png) ## Browser Support ![](https://i.imgur.com/nW14pzZ.png) --- ## 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) ![](https://i.imgur.com/5n6id84.png) --- ## **註冊 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 文件說明 >![](https://i.imgur.com/mlAsaS9.png) ## 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 說明: ![](https://i.imgur.com/UuSUSAi.png) ---- ### 作法 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 ![](https://i.imgur.com/KWybN0z.png) ### cache v1 --- NEW cache > ```javascript= > const CACHE_NAME = 'v2' >after ![](https://i.imgur.com/dPaW29L.png) ***cached files*** ```javascript= const urlsToCache = [ 'index.html', 'about.html', '/css/style.css', '/js/main.js' ]; ``` **Storage Data** ![](https://i.imgur.com/qEXAtBt.png) ![](https://i.imgur.com/btpOWzy.gif) # 可能會遇到的問題 * 安裝失敗不會告知原因: > 如果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 推播的各種狀態 ![](https://i.imgur.com/TzwFAoY.png) --- **2020-06-02**

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully