Luke
Luke

Reputation: 23690

How does Stack Exchange check for new posts/comments?

I've been watching the "Network" section in the Chrome developer tools to see what activity there is on a new and active post here at Stack Overflow.

I expected to see periodic network activity to check a script for updated elements on the page (such as new comment or answer posted) - But there doesn't appear to be one!

I just implemented a periodic "heartbeat" for some pages on my site.

Does Stack Overflow achieve some sort of "push" check for new posts?

Upvotes: 3

Views: 209

Answers (1)

double-beep
double-beep

Reputation: 5519

Using websockets.

On page load, the site connects to the wss://qa.sockets.stackexchange.com/ websocket and sends a <site_id>-question-<question_id> message to it (e.g. 1-question-14384446), therefore subscribing to question events (new answers, new comments, post deletion, score change, etc.).

Here's a JavaScript example. To test if it works, you can add a comment under your question or this answer:

const socket = new WebSocket('wss://qa.sockets.stackexchange.com/');
socket.onopen = () => {
  socket.send('1-question-14384446'); // subscribe to question events
  console.log('Listening for new comments...');
};

socket.onmessage = ({ data }) => {
  const obj = JSON.parse(data);

  // sent every 5 minutes to check if connection is alive
  if (obj.action === 'hb') {
    socket.send('pong');
    return;
  }

  const { a: type, commentid } = JSON.parse(obj.data);
  if (type !== 'comment-add') return; // not a comment

  console.log('New comment with id', commentid);
};
socket.onerror = console.error; // just in case

Reference:

Upvotes: 0

Related Questions