Skip to content

Commit

Permalink
add offline mode
Browse files Browse the repository at this point in the history
  • Loading branch information
caiguanhao committed Jan 23, 2024
1 parent 565f6bd commit da4184a
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 7 deletions.
37 changes: 30 additions & 7 deletions wasm/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,20 @@
</div>
</div>
</template>
<p>
<template v-if="!loading">
<a href v-on:click.prevent="example">Show me example</a>
/
</template>
<a href="https://github.com/caiguanhao/opencc">View on GitHub</a>
</p>
<div class="d-sm-flex justify-content-between">
<div>
<template v-if="!loading">
<a href v-on:click.prevent="example">Show me example</a>
/
</template>
<a href="https://github.com/caiguanhao/opencc">View on GitHub</a>
</div>
<div v-if="pwa !== null">
<label class="mb-0">
<input type="checkbox" v-model="pwa"><small class="ml-2">Enable Offline Mode (PWA)</small>
</label>
</div>
</div>
</div>

<script>
Expand All @@ -52,6 +59,7 @@
el: '#app',
data: {
loading: false,
pwa: null,
input: null,
output: null,
dict: window.localStorage ? window.localStorage.getItem('dict') : null,
Expand Down Expand Up @@ -92,6 +100,17 @@
dict (val) {
if (window.localStorage) window.localStorage.setItem('dict', val)
this.convert()
},
pwa () {
if (!window.navigator.serviceWorker) return
if (this.pwa === true) {
window.navigator.serviceWorker.register('./service-worker.js')
} else if (this.pwa === false) {
window.navigator.serviceWorker.getRegistration().then(reg => {
if (reg) reg.unregister()
})
window.caches.delete('opencc')
}
}
},
methods: {
Expand Down Expand Up @@ -134,6 +153,10 @@
WebAssembly.instantiateStreaming(fetch('opencc.wasm'), go.importObject).then(result => {
return go.run(result.instance)
})

if (window.caches) {
window.caches.has('opencc').then(has => this.pwa = has)
}
}
})
})()
Expand Down
34 changes: 34 additions & 0 deletions wasm/service-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
var cacheName = 'opencc'

var filesToCache = [
'./',
'./index.html',
'./wasm_exec.js',
'./opencc.wasm',
'https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css',
'https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js'
]

self.addEventListener('install', function (e) {
e.waitUntil(
caches.open(cacheName).then(function (cache) {
return cache.addAll(filesToCache)
})
)
})

self.addEventListener('fetch', function (e) {
e.respondWith(
caches.match(e.request).then(function (response) {
return fetch(e.request).then(res => {
return caches.open(cacheName).then(function (cache) {
return cache.put(e.request, res.clone()).then(function () {
return res
})
})
}).catch(() => {
return response
})
})
)
})

0 comments on commit da4184a

Please sign in to comment.