Real-Time News Streaming with JavaScript and Websocket
The example below represents a simple WebSocket client implemented in vanilla JavaScript that can be executed in your browser, and displays new articles as soon as they are published.
Simply copy/paste the code into the file client.html
and open it in your browser. Once the client is connected, the app prints a "Socket connected" status and newly published articles are shown in your browser.
The keepConnectionAlive
function sends a ping every 20 seconds to the news streaming server. The function is required for the connection to stay open as otherwise the server automatically closes the stream.
Remember to replace
YOUR_API_KEY
with your API key.
<!DOCTYPE html>
<html>
<head>
<script>
const apiKey = 'YOUR_API_KEY';
const ws = new WebSocket(
'ws://stream.newsfilter.io/socket.io/?EIO=3&transport=websocket&apiKey=' +
apiKey
);
// keep connection alive
const keepConnectionAlive = () => {
setInterval(() => {
ws.send(40);
}, 20000); // send ping every 20 seconds
};
ws.addEventListener('open', (event) => {
keepConnectionAlive();
document.getElementById('connectionStatus').innerHTML =
'Socket connected';
});
ws.addEventListener('close', (event) => {
document.getElementById('connectionStatus').innerHTML = 'Socket closed';
});
ws.addEventListener('message', (event) => {
// only listen to messages starting with code 42
if (event.data.startsWith('42')) {
// remove trailing "42" in message content
const messageString = event.data.replace(/^42/, '');
// convert message string into javascript object
const message = JSON.parse(messageString);
// extract articles array from message
const articles = message[1].articles;
const text = document.createTextNode(articles[0].title),
el = document.createElement('li'),
messages = document.getElementById('messages');
el.appendChild(text);
messages.insertBefore(el, messages.firstChild);
}
});
</script>
</head>
<body>
<div id="connectionStatus"></div>
<ul id="messages"></ul>
</body>
</html>