metasearch/index.js
2023-10-14 14:41:06 +02:00

43 lines
1.1 KiB
JavaScript

// 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')
})