-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathmain.swift
48 lines (38 loc) · 1.32 KB
/
main.swift
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
import JavaScriptKit
import JavaScriptEventLoop
let alert = JSObject.global.alert.function!
let document = JSObject.global.document
var divElement = document.createElement("div")
divElement.innerText = "Hello, world"
_ = document.body.appendChild(divElement)
var buttonElement = document.createElement("button")
buttonElement.innerText = "Alert demo"
buttonElement.onclick = .object(JSClosure { _ in
alert("Swift is running on browser!")
return .undefined
})
_ = document.body.appendChild(buttonElement)
private let jsFetch = JSObject.global.fetch.function!
func fetch(_ url: String) -> JSPromise {
JSPromise(jsFetch(url).object!)!
}
JavaScriptEventLoop.installGlobalExecutor()
struct Response: Decodable {
let uuid: String
}
var asyncButtonElement = document.createElement("button")
asyncButtonElement.innerText = "Fetch UUID demo"
asyncButtonElement.onclick = .object(JSClosure { _ in
Task {
do {
let response = try await fetch("https://httpbin.org/uuid").value
let json = try await JSPromise(response.json().object!)!.value
let parsedResponse = try JSValueDecoder().decode(Response.self, from: json)
alert(parsedResponse.uuid)
} catch {
print(error)
}
}
return .undefined
})
_ = document.body.appendChild(asyncButtonElement)