forked from honkinglin/simple-pwa-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
51 lines (43 loc) · 1.47 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const apiKey = 'fa35a325ddfa4c4798102ebb76809bbb';
const main = document.querySelector('main');
const sourceSelector = document.querySelector('#sourceSelector');
const defaultSource = 'techcrunch'
window.addEventListener('load', async e => {
updateNews();
await updateSources();
sourceSelector.value = defaultSource;
sourceSelector.addEventListener('change', e => {
updateNews(e.target.value);
});
if ('serviceWorker' in navigator) {
try {
navigator.serviceWorker.register('sw.js');
console.log('SW registered');
} catch (error) {
console.log('SW reg failed');
}
}
});
async function updateSources() {
const res = await fetch(`https://newsapi.org/v2/sources?apiKey=${apiKey}`);
const json = await res.json();
sourceSelector.innerHTML = json.sources
.map(src => `<option value="${src.id}">${src.name}</option>`)
.join('\n');
}
async function updateNews(source = defaultSource) {
const res = await fetch(`https://newsapi.org/v2/top-headlines?sources=${source}&apiKey=${apiKey}`);
const json = await res.json();
main.innerHTML = json.articles.map(createArticle).join('\n');
}
function createArticle(article) {
return `
<div class="article">
<a href="${article.url}">
<h2>${article.title}</h2>
</a>
<img src="${article.urlToImage}" />
<p>${article.description}</p>
</div>
`;
}