Listen in a web page
Show live messages in a web page with the browser WebSocket.
A web page can connect to OpenSync with the browser's WebSocket, also when the page is on another address. Use a token limited to the channels the page needs: everyone who opens the page can read the token in its source.
The page
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Live orders</title>
</head>
<body>
<ul id="orders"></ul>
<script>
var ws = new WebSocket('wss://sync.example.com/?token=YOUR_TOKEN&app=Browser');
ws.onmessage = function(e) {
var msg = JSON.parse(e.data);
if (msg.channel !== 'orders')
return;
var li = document.createElement('li');
li.textContent = msg.method + ' ' + JSON.stringify(msg.body);
document.getElementById('orders').appendChild(li);
};
</script>
</body>
</html>The init message has no channel, so the page skips it.
Send from the page
The page can also send to a channel through the same connection:
ws.send(JSON.stringify({ type: 'notify', channel: 'chat', body: { text: 'Hi' } }));Why not EventSource or fetch?
OpenSync does not send CORS headers. A browser therefore blocks an EventSource stream, and a JSON fetch to /sync/, from a page on another address. WebSocket is not affected. Send data to /sync/ from your server instead.