Initial commit

This commit is contained in:
Danny Harpigny 2023-10-14 14:41:06 +02:00
commit b37d5417b7
4 changed files with 100 additions and 0 deletions

5
data.json Normal file
View File

@ -0,0 +1,5 @@
{
"instances": [
"https://searxng.no-logs.com/search"
]
}

23
index.html Normal file
View File

@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="referrer" content="no-referrer">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#info { color: gray; }
#info.error { color: red; }
</style>
<script type="module" src="index.js"></script>
</head>
<body>
<div class="search-box">
<form id="search">
<input name="query" type="text" placeholder="Query">
<input type="submit" value="Search">
</form>
<p id="info"></p>
</div>
</body>
</html>

42
index.js Normal file
View File

@ -0,0 +1,42 @@
// Register service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js', {
type: 'module'
})
.then(() => console.log('sw ok'))
.catch(() => console.log('sw not ok'))
}
var data = {}
const infoEl = document.getElementById('info')
const formEl = document.getElementById('search')
// Register event listeners
formEl.addEventListener('submit', (event) => {
if ('instances' in data && data.instances.length > 0) {
event.preventDefault()
// Random instance
const n = Math.floor(Math.random() * data.instances.length)
const instanceURL = data.instances[n]
// Assign URL
const params = new URLSearchParams({
q: formEl.query.value
})
const url = `${instanceURL}?${params.toString()}`
location.assign(url)
}
})
// Fetch data
await fetch('./data.json')
.then(req => req.json())
.then(newData => { data = newData })
.then(() => {
infoEl.textContent = `${data.instances.length} instances`
})
.catch(err => {
console.error(err)
infoEl.textContent = err.toString()
infoEl.classList.add('error')
})

30
sw.js Normal file
View File

@ -0,0 +1,30 @@
const cacheName = 'v1'
self.addEventListener('install', (event) => {
event.waitUntil(
caches
.open(cacheName)
.then(cache => cache.addAll([
'.',
'./index.html',
'./index.js',
'./index.css',
'./instances.json'
]))
)
})
self.addEventListener('activate', (_event) => {
})
self.addEventListener('fetch', async (event) => {
const res = await fetch(event.request)
if (!res.ok) {
const cachedRes = await caches.match(event.request)
if (cachedRes) {
event.respondWith(cachedRes)
return
}
}
event.respondWith(res)
})