Skip to content

Commit

Permalink
fix: handle base64 responses
Browse files Browse the repository at this point in the history
  • Loading branch information
jonaskuske authored Nov 30, 2023
1 parent 45dd0be commit 6ef70d5
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 81 deletions.
5 changes: 4 additions & 1 deletion modules/utils.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ export const fetchData = async url => {
try {
const response = await fetch(getCorsURL(url)).then(validateResponse)
const body = await response.json()
return body.contents
if (body.contents?.match(/^data:.+;base64,/)) {
return atob(body.contents.replace(/^data:.+;base64,/, ""))
}
return body.contents
} catch (error) {
const response = await fetch(getFallbackURL(url)).then(validateResponse)
return response.text()
Expand Down
160 changes: 80 additions & 80 deletions serviceworker.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
const CACHE_NAME = 'fluent-tab-v14'
const CACHE_NAME = "fluent-tab-v15"

const staticAssets = [
'.',
'./index.html',
'./index.css',
'./index.mjs',
'./modules/cheerio.mjs',
'./modules/edit-name.mjs',
'./modules/fluent-button.mjs',
'./modules/scrape-html.mjs',
'./modules/utils.mjs',
'./images/smiley.png',
'./images/background.jpg',
".",
"./index.html",
"./index.css",
"./index.mjs",
"./modules/cheerio.mjs",
"./modules/edit-name.mjs",
"./modules/fluent-button.mjs",
"./modules/scrape-html.mjs",
"./modules/utils.mjs",
"./images/smiley.png",
"./images/background.jpg",
]

// get the filenames to cache from the parcel-manifest and add them to cache
self.addEventListener('install', event => {
event.waitUntil(
self.addEventListener("install", (event) => {
event.waitUntil(
caches
.open(CACHE_NAME)
.then((cache) => cache.addAll(staticAssets.map((url) => `${url}?v=${CACHE_NAME}`)))
Expand All @@ -25,84 +25,84 @@ self.addEventListener('install', event => {
})

/* delete old caches on activation */
self.addEventListener('activate', event => {
const allowedCaches = [CACHE_NAME]
event.waitUntil(
caches.keys().then(cacheNames => {
const cacheDeletePromises = cacheNames.map(cacheName => {
if (!allowedCaches.includes(cacheName)) {
return caches.delete(cacheName)
}
})
return Promise.all(cacheDeletePromises)
})
)
self.addEventListener("activate", (event) => {
const allowedCaches = [CACHE_NAME]
event.waitUntil(
caches.keys().then((cacheNames) => {
const cacheDeletePromises = cacheNames.map((cacheName) => {
if (!allowedCaches.includes(cacheName)) {
return caches.delete(cacheName)
}
})
return Promise.all(cacheDeletePromises)
}),
)
})

const checkResponseStatus = r =>
new Promise((res, rej) => {
if ((r.status >= 200 && r.status < 300) || r.status === 0) res(r)
else rej(r.statusText)
})
const checkResponseStatus = (r) =>
new Promise((res, rej) => {
if ((r.status >= 200 && r.status < 300) || r.status === 0) res(r)
else rej(r.statusText)
})
/* Helper functions to determine whether requests/responses should be cached */
const isRequestCacheable = request => {
const url = new URL(request.url)
if (url.protocol === 'chrome-extension:') return false
const isRequestCacheable = (request) => {
const url = new URL(request.url)
if (url.protocol === "chrome-extension:") return false

return true
return true
}
const isResponseCacheable = response => {
// don't cache opaque response to prevent exceeding cache size quota
// see https://cloudfour.com/thinks/when-7-kb-equals-7-mb/
if (response.status === 0 || response.type === 'opaque') return false
const isResponseCacheable = (response) => {
// don't cache opaque response to prevent exceeding cache size quota
// see https://cloudfour.com/thinks/when-7-kb-equals-7-mb/
if (response.status === 0 || response.type === "opaque") return false

return true
return true
}

const requestFailingWith404 = event => {
return fetch(event.request).catch(() => {
const body = JSON.stringify({
error: "Sorry, you're offline. Try again once you have a working internet connection.",
})
const headers = { 'Content-Type': 'application/json' }
return new Response(body, { status: 404, statusText: 'Not Found', headers })
})
const requestFailingWith404 = (event) => {
return fetch(event.request).catch(() => {
const body = JSON.stringify({
error: "Sorry, you're offline. Try again once you have a working internet connection.",
})
const headers = { "Content-Type": "application/json" }
return new Response(body, { status: 404, statusText: "Not Found", headers })
})
}
const requestThenCache = (event, cache) => {
return fetch(event.request)
.then(checkResponseStatus)
.then(response => {
if (isResponseCacheable(response)) {
cache.put(event.request, response.clone())
}
return response
})
.catch(() => cache.match(event.request))
return fetch(event.request)
.then(checkResponseStatus)
.then((response) => {
if (isResponseCacheable(response)) {
cache.put(event.request, response.clone())
}
return response
})
.catch(() => cache.match(event.request))
}

self.addEventListener('fetch', event => {
// if request should not be cached: respond with normal 404 fetch and return
if (!isRequestCacheable(event.request)) {
event.respondWith(requestFailingWith404(event))
return
}
self.addEventListener("fetch", (event) => {
// if request should not be cached: respond with normal 404 fetch and return
if (!isRequestCacheable(event.request)) {
event.respondWith(requestFailingWith404(event))
return
}

// ! ignore query strings
const requestURL = event.request.url
const request = requestURL.includes('?')
? new Request(requestURL.substring(requestURL.indexOf('?') + 1))
: event.request
// ! ignore query strings
const requestURL = event.request.url
const request = requestURL.includes("?")
? new Request(requestURL.substring(requestURL.indexOf("?") + 1))
: event.request

event.respondWith(
caches
.match(request)
.then(checkResponseStatus)
.then(response => {
return caches.open(CACHE_NAME).then(cache => {
if (navigator.onLine) requestThenCache(event, cache)
return response
})
})
.catch(() => caches.open(CACHE_NAME).then(cache => requestThenCache(event, cache)))
)
event.respondWith(
caches
.match(request)
.then(checkResponseStatus)
.then((response) => {
return caches.open(CACHE_NAME).then((cache) => {
if (navigator.onLine) requestThenCache(event, cache)
return response
})
})
.catch(() => caches.open(CACHE_NAME).then((cache) => requestThenCache(event, cache))),
)
})

0 comments on commit 6ef70d5

Please sign in to comment.