try it out in chrome canary today - https://www.google.com/chrome/browser/canary.html
no need for canary - I just updated to chrome 61 - it works!
just make sure the page is served from a webserver and not loaded from the local filesystem
wikipedia search in bleeding edge js - classes with async/await in modules!
<!doctype html>
<!-- index.html -->
<head>
<title>Wikipedia Search</title>
</head>
<body>
<h1>Wikipedia Search</h1>
<p><form>
<input name=srsearch type=search value=music>
<input name=action type=hidden value=query>
<input name=list type=hidden value=search>
<input name=format type=hidden value=json>
<input name=formatversion type=hidden value=2>
<input name=utf8 type=hidden>
<input name=origin type=hidden value=*>
<p><output name=out></output>
</form>
<script src=wikisearch.js type=module></script>
<!-- for browsers that do not yet support modules -->
<script nomodule>
document.addEventListener("DOMContentLoaded", ()=>{
document.querySelector("form").out.innerHTML="<h2>Modules are not supported</h2>"
})
</script>
</body>
</html>
WikiSearch module controls search ui - provides form data to WikiService module to obtain wikipedia results
// wikisearch.js
import {WikiService} from "./wikiservice.js"
class WikiSearch {
constructor(form, svc) {
this.form=form
this.svc=svc
}
init() {
this.form.addEventListener("submit", async e=>{
e.preventDefault()
const query=new FormData(this.form)
const hits=await this.svc.get(query)
const html=hits? hits.html(): "<p>Wikipedia search failure</p>"
this.form.out.innerHTML=html
})
}
}
document.addEventListener("DOMContentLoaded", ()=>{
const form=document.querySelector("form")
const wsvc=new WikiService("https://en.wikipedia.org")
const wsrch=new WikiSearch(form, wsvc)
wsrch.init()
})
WikiHits module holds results data - provides data in html table form
// wikihits.js
class WikiHits {
constructor(src) {
this.src=src
}
get hits() {
return this.hits_
}
set hits(hits) {
this.hits_=hits
}
html() {
const a=this.hits
let s=`<p><table>`
s+="<tr><th>Title<th>Snippet"
for(let o of a) {
const href=`${this.src}?curid=${o.pageid}`
s+=`<tr><td><a href=${href} target=_blank>${o.title}</a>`
s+=`<td>${o.snippet}`
}
s+="</table>"
return s
}
}
export {WikiHits}
WikiService module retrieves search hits from wikipedia - returns WikiHits object
// wikiservice.js
import {WikiHits} from "./wikihits.js"
class WikiService {
constructor(wiki) {
this.wiki=wiki
this.api=wiki + "/w/api.php"
}
async get(query) {
try {
const rsp=await fetch(this.api, {method:"POST", body:query})
if(!rsp.ok) return null
const data=await rsp.json()
const hits=new WikiHits(this.wiki)
hits.hits=data.query.search
return hits
} catch(err) {
console.log(`fetch error ${err}`)
return null
}
}
}
export {WikiService}
who still thinks this is no big deal?