-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbrowser-answer.html
81 lines (77 loc) · 2.73 KB
/
browser-answer.html
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<!DOCTYPE html>
<html>
<head>
<title>WebRTC IPFS Signaling Answerer</title>
<script src="https://unpkg.com/[email protected]/dist/index.min.js"></script>
<!-- <script src="js-ipfs.min.js"></script> -->
<script src="browser.js"></script>
</head>
<body>
<h3>WebRTC IPFS Signaling Answerer</h3>
<div>
<strong>URL to offer:</strong>
<a id="offerUrl"></a>
<button id="regenerate">Restart and Regenerate</button>
</div>
<hr />
<div>
<label for="chat">Chat:</label>
<textarea id="chat" style="width: 100%" rows="15" placeholder="(waiting for chat to start)" readonly></textarea>
<div style="display: flex">
<label for="message">Send Message: </label>
<input id="message" type="text" style="flex: 1" disabled>
</div>
</div>
<script>
// Make a random URL hash if not given
createWindowHashIfNotPresent()
// Grab the URL, replace answer w/ offer
const offerUrl = window.location.href.replace('offer.html', 'answer.html')
const offerUrlAnchor = document.getElementById('offerUrl')
offerUrlAnchor.href = offerUrl
offerUrlAnchor.innerText = offerUrl
// Refresh if asked
document.getElementById('regenerate').onclick = () => {
window.location.hash = ''
location.reload()
}
// Create IPFS and do everything else once ready
newIPFS(ipfs => {
// Create new RTC conn
const pc = new RTCPeerConnection({
// Could have a TURN server too, not worth it for the demo
iceServers: [{ urls: 'stun:stun.l.google.com:19302'}]
})
// Setup chat channel
pc.ondatachannel = e => setupChatChannel(e.channel)
// Add the handlers
pc.oniceconnectionstatechange = e => console.log('RTC connection state change', pc.iceConnectionState)
pc.onicecandidate = e => {
// No candidate means we're done
if (e.candidate === null) {
// Write the answer
debug('Writing answer')
ipfsPublish(ipfs, JSON.stringify(pc.localDescription), () => {
debug('Added answer')
})
}
}
// Wait for offer
debug('Waiting for offer')
let gotOffer = false
ipfsSubscribe(
ipfs,
data => {
const obj = JSON.parse(data)
debug('Received data', obj)
if (obj.type == 'offer') {
gotOffer = true
pc.setRemoteDescription(new RTCSessionDescription(obj)).then(() => {
pc.createAnswer().then(d => pc.setLocalDescription(d)).catch(console.error)
}).catch(console.error)
}
}, () => { })
})
</script>
</body>
</html>